in reply to Regexp and substitution question

As other people have noted, a subsequent successful match resets the captured values. However, this doesn't have to create a problem; you can use the list behavior of captures in a regex to save them for reuse.

#!/usr/bin/perl -w use strict; my $line="One two three four five"; my @chunks; if(@chunks = $line =~ m/(one)\s(two)\s(three)\s(four)\s(five)/i){ $chunks[0] =~ s/One/ONE/; # Change the first chunk $chunks[1] =~ s/two/tWo/; # Change the second chunk # ... } print "@chunks\n";

Output:

ONE tWo three four five

--
"Language shapes the way we think, and determines what we can think about."
-- B. L. Whorf

Replies are listed 'Best First'.
Re^2: Regexp and substitution question
by pemungkah (Priest) on Aug 29, 2010 at 00:27 UTC
    Absolutely - I can't emphasize enough how important it is to get in the habit of explicitly capturing your matches. It's easy to get lazy about using the values right away, and then your program develops mysterious bugs when someone else adds a "harmless" function call that invokes something else that internally does a pattern match, but only sometimes...

    I also recommend getting into the habit of naming your captures; that way it's much clearer: "now does $capture[4] contain the right value, or was it $capture[3]?". If you do this:

    my($name, $age, $weight) = ($line =~ /$pattern/);
    you'll be much less likely to set someone's age to 180 and their weight to 40.