How do I assign a value to a variable and modify it with a regular expression, in one statement?

You want to do:

    use strict;
    use warnings;

    $string1 = $string2;
    $string1 =~ s/\s+//g;

in one line.

Solution: Parentheses!

The most common and recommended solution is:

    ($string1 = $string2) =~ s/\s+//g;

which has the effect of making a copy of $string2 in $string1, and then applying the substitution to $string1.

However another solution is:

    s/\s+//g for $string1 = $string2;
Revision: 1.5 [Top]