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/libThe 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)
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access