Copying and Substituting Simultaneously
Problem
You’re tired of constantly using two separate statements with redundant information, one to copy and another to substitute.
Solution
Instead of:
$dst = $src; $dst =~ s/this/that/;
use:
($dst = $src) =~ s/this/that/;
Discussion
Sometimes what you wish you could have is the new string, but you don’t care to write it in two steps.
For example:
# strip to basename ($progname = $0) =~ s!^.*/!!; # Make All Words Title-Cased ($capword = $word) =~ s/(\w+)/\u\L$1/g; # /usr/man/man3/foo.1 changes to /usr/man/cat3/foo.1 ($catpage = $manpage) =~ s/man(?=\d)/cat/;
You can even use this technique on an entire array:
@bindirs = qw( /usr/bin /bin /usr/local/bin );
for (@libdirs = @bindirs) { s/bin/lib/ }
print "@libdirs\n";
/usr/lib /lib /usr/local/lib
The parentheses are required when combining an assignment if you wish
to change the result in the leftmost variable. Normally, the result
of a substitution is its success: either ""
for
failure, or the number of times the substitution was done. Contrast
this with the preceding examples where the parentheses surround the
assignment itself. For example:
($a = $b) =~ s/x/y/g; # copy $b and then change $a $a = ($b =~ s/x/y/g); # change $b, count goes in $a
See Also
The “Variables” section of Chapter 2 of
Programming Perl, and the “Assignment
Operators” section of perlop
(1)
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.