in reply to Determing whether a regexp has capturing matches

You don't need to set $1 before the match. In fact, I think you can't.

$ perl -le '$1=undef;' Modification of a read-only value attempted at -e line 1.

$1 will be set to undef after a match with no parentheses.

"1234"=~/(\d)/; print "$1\n"; "1234"=~/34/; print "$1\n"; print "undef\n" if ! defined $1;

Prints:

1 undef

This doesn't work when a regex had capturing parentheses that didn't match. Just like the "no parentheses" case above, this also prints "undef":

"1234"=~/(x)?34/; print "undef" if ! defined $1;

Replies are listed 'Best First'.
Re^2: Determing whether a regexp has capturing matches
by adrianh (Chancellor) on Feb 27, 2007 at 15:58 UTC
    $1 will be set to undef after a match with no parentheses.

    Is this documented behaviour? I could have sworn I'd used a perl at some point where $1 persisted unless you made another captured match. I could, of course, be making shit up :-)