Logo

Programming-Idioms

History of Idiom 296 > diff from v8 to v9

Edit summary for version 9 by skeletonkey:
[Perl] Add description of what's going on.

Version 8

2022-02-18, 13:35:18

Version 9

2022-02-18, 13:37:21

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
my $x2 = $x;
$x2 =~ s/y([^y]*)$/z$1/;
Code
my $x2 = $x;
$x2 =~ s/y([^y]*)$/z$1/;
Comments bubble
Using regex to find the last 'y' in the string and capture anything after it. Then replace the 'y' with 'z' and put the captured info back in ($1).
Doc URL
https://perldoc.perl.org/functions/s
Doc URL
https://perldoc.perl.org/functions/s
Demo URL
http://codepad.org/LwnULDDE
Demo URL
http://codepad.org/LwnULDDE