in reply to Re: Re: Regular Expression Question
in thread What happens with empty $1 in regular expressions? (was: Regular Expression Question)

The proper way to protect yourself from using unintended old values in $1 and friends is to program defensively and check if a pattern match succeeded before trying to use captured subexpressions (as previous messages in this thread have shown).
Well, that's a way. Another way is to stylistically outlaw all uses of $1 et seq, except in the right side of a substitution. Any other "capturing" should be done as list-context assignment:
my ($first, $second) = $source =~ /blah(this)blah(that)blah/;
Then it's very clear what the scope and origination of $first and $second are.

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: Re: Re: Re: Regular Expression Question
by danger (Priest) on Feb 28, 2001 at 23:29 UTC

    Indeed, that's true enough -- I was trying to make a more general statement but failed to sufficiently generalize away from the specific problem of resuing old $1 etc. The more general point being to check the success of an operation before doing things that depend on the operation having succeeded. Thus, even when doing a list assignment of subexpressions from a match, one will generally want to test that the match succeeded prior to using the results:

    if(my ($first, $second) = $source =~ /blah(this)blah(that)blah/){ print "$first $second\n"; }