in reply to ?: and saving backreferences
You don't need clutter just to use a variable. Remember that a do block returns the last evaluated expression. In this example, I assign that result to @memories, which puts the matches in list context so they return the parts they remembered as a list.
$_ = 'abcdefghijk'; foreach my $left ( 0 .. 1 ) { my @memories = do { if( $left ) { /ab(..)ef/ } else { /fg(..)jk/ } }; print "Left $left: caught @memories\n" }
Once I have the memories in the array, I can easily pull out any element that I like. If the match fails, @memories is empty. I don't have to deal with a lot of gymnastics to figure out is the match succeeded. Without knowing that the match suceeded, you shouldn't use any of the number variables ($1, $2, and so on).
Remember that $1 and so on are package variables, and that they persist until the next successful pattern match. It doesn't have anything to do with lexical scope. Actually, perlvar says:
$<digits> Contains the subpattern from the corresponding set of capturing parentheses from the last pattern match, not counting patterns matched in nested blocks that have been exited already. (Mnemonic: like \digits.) These variables are all read-only and dynamically scoped to the current BLOCK.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: ?: and saving backreferences
by throop (Chaplain) on Dec 08, 2006 at 21:05 UTC |