Book HomePerl CookbookSearch this book

6.1. 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)


Previous: 6.0. IntroductionPerl CookbookNext: 6.2. Matching Letters
6.0. IntroductionBook Index6.2. Matching Letters

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.