Logo

Programming-Idioms

History of Idiom 296 > diff from v17 to v18

Edit summary for version 18 by jgpuckering:
New Perl implementation by user [jgpuckering]

Version 17

2022-09-05, 20:12:16

Version 18

2022-10-30, 17:48:44

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;
substr($x2, rindex($x, $y), length($y)) = $z;

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.