in reply to ?: and saving backreferences

None of those are particularly useful in practice since they don't check if the regexp matched successfully (and don't lend well to being modified to do so). When the regexp doesn't match, $1 and similar variables are left unchanged and therefore meaningless. What follows are more practical patterns.

Using ?::

my $re = $left ? qr/ab(..)ef/ : qr/gh(..)jk/; /$re/ or die("Bad data"); print "Caught $1\n"

Using if/elsif:

my $re; if (...) { $re = qr/.../ } elsif (...) { $re = qr/.../ } elsif (...) { $re = qr/.../ } else { die '...' } /$re/ or die("Bad data"); print "Caught $1\n"

Using a lookup table:

my %re_lookup = ( ... => qr/.../, ... => qr/.../, ... => qr/.../, ); /$re_lookup{...}/ or die("Bad data"); print "Caught $1\n"

Replies are listed 'Best First'.
Re^2: ?: and saving backreferences
by dewey (Pilgrim) on Dec 06, 2006 at 03:26 UTC
    Maybe I'm missing something, but it seems fairly easy to modify OP's code to check for a match:
    ($left ? /ab(..)ef/ : /gh(..)jk/) or die("Bad data");
    This line is less readable in some ways than your suggested patterns, but it doesn't introduce any new variables.
    Note: I got some results that looked funny until I replaced OP's (..) with (.*) in the regexen, watch out for that!
    ~dewey