because the $1 backreference is lost once you exit the scope of the if/else. So you can clutter things up with an extra variable:$_ = 'abcdefghijk'; my($left) =1; if($left){ /ab(..)ef/} else{ /gh(..)jk/}; print "Caught $1\n"
or you can use ?: and not lose the backreference$_ = 'abcdefghijk'; my($left, $var) =1; if($left){ ($var) = /ab(..)ef/} else{ ($var) = /gh(..)jk/}; print "Caught $var\n"
Of course, simple examples aren't as compelling as complex ones (because the amount of extra obscurity and work are small when the example is simple.) But if the pattern match is complex (eg when I'm trying to pull out $4 instead of $1) or when I'm ganging different patternmatches together. In the example below, $verbpat, $nounpat, $preppat are three similar patterns; I want to pull $4 out of each$_ = 'abcdefghijk'; my($left) =1; $left ? /ab(..)ef/ : /gh(..)jk/; print "Caught $1\n"
So here's one more time that ?: is superior to if/else - when you want the backreference for a little longer while.$verbtest ? /$verbpat/ : $nountest ? /$nounpat/ : $preptest ? /$preppat/ : die 'No catch on $_'; $catch = $4;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: ?: and saving backreferences
by brian_d_foy (Abbot) on Dec 06, 2006 at 06:14 UTC | |
by throop (Chaplain) on Dec 08, 2006 at 21:05 UTC | |
|
Re: ?: and saving backreferences
by ikegami (Patriarch) on Dec 05, 2006 at 23:50 UTC | |
by dewey (Pilgrim) on Dec 06, 2006 at 03:26 UTC | |
|
Re: ?: and saving backreferences
by BUU (Prior) on Dec 06, 2006 at 05:31 UTC | |
by ikegami (Patriarch) on Dec 06, 2006 at 06:10 UTC | |
by BUU (Prior) on Dec 06, 2006 at 06:24 UTC |