O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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)

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required