Logo

Programming-Idioms

History of Idiom 296 > diff from v19 to v20

Edit summary for version 20 by jgpuckering:
[Perl] Added Demo URL

Version 19

2022-10-30, 17:53:57

Version 20

2022-11-03, 05:38:35

Idiom #296 Replace last occurrence of substring

Assign to x2 the value of string x with the last occurrence of y replaced by z.
If y is not contained in x, then x2 has the same value as x.

Idiom #296 Replace last occurrence of substring

Assign to x2 the value of string x with the last occurrence of y replaced by z.
If y is not contained in x, then x2 has the same value as x.

Variables
x2,x,y,z
Variables
x2,x,y,z
Extra Keywords
substring substitute
Extra Keywords
substring substitute
Code
$x = 'A BB CCC this DDD EEEE this FFF';
$y = 'this';
$z = 'that';

$x2 = $x;
$pos = rindex $x, $y;
substr($x2, $pos, length($y)) = $z
    unless $pos == -1;

print $x2;
Code
$x = 'A BB CCC this DDD EEEE this FFF';
$y = 'this';
$z = 'that';

$x2 = $x;
$pos = rindex $x, $y;
substr($x2, $pos, length($y)) = $z
    unless $pos == -1;

print $x2;
Comments bubble
perl substr can be used as an lvalue, which is ideal here. We use rindex to find the last occurence of substring $y in $x and use that position in a substr of a copy of $x called $x2. Assigning $z to the substring replaces it -- but we skip that if rindex didn't find the substring.
Comments bubble
perl substr can be used as an lvalue, which is ideal here. We use rindex to find the last occurence of substring $y in $x and use that position in a substr of a copy of $x called $x2. Assigning $z to the substring replaces it -- but we skip that if rindex didn't find the substring.
Doc URL
https://perldoc.perl.org/functions/substr
Doc URL
https://perldoc.perl.org/functions/substr
Demo URL
https://ideone.com/RGZonh