Logo

Programming-Idioms

History of Idiom 296 > diff from v18 to v19

Edit summary for version 19 by jgpuckering:
[Perl] Added condition to satisfy the non-contained constraint; added Doc URL

Version 18

2022-10-30, 17:48:44

Version 19

2022-10-30, 17:53:57

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;
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.
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