6.1. Copying and Substituting SimultaneouslyProblemYou're tired of constantly using two separate statements with redundant information, one to copy and another to substitute. DiscussionSometimes 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";
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 ($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 AlsoThe "Variables" section of Chapter 2 of Programming Perl , and the "Assignment Operators" section of perlop (1) Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|