Copying and Substituting Simultaneously (Perl Cookbook, 2nd Edition)

## 6.1. Copying and Substituting Simultaneously

### 6.1.1. Problem

You're tired of using two separate statements with redundant information, one to copy and another to substitute.

### 6.1.2. Solution

Instead of:

>     $dst = $src;
>     $dst =~ s/this/that/;

use:

>     ($dst = $src) =~ s/this/that/;

### 6.1.3. Discussion

Sometimes you wish you could run a search and replace on a copy of a string, but you don't care to write this in two separate steps. You don't have to, because you can apply the regex operation to the result of the copy operation.

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

Because of precedence, parentheses are required when combining an assignment if you wish to change the result in the leftmost variable. The result of a substitution is its success: either "" for failure, or an integer 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;      # 1: copy $b and then change $a
>      $a = ($b  =~ s/x/y/g);     # 2: change $b, count goes in $a
>      $a =  $b  =~ s/x/y/g;      # 3: same as 2

### 6.1.4. See Also

The "Variables" section of Chapter 2 of Programming Perl, and the "Assignment Operators" section of perlop(1) and Chapter 3 of Programming Perl

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