morgon has asked for the wisdom of the Perl Monks concerning the following question:
in scripts I usually match like this:
but sometimes I do one-liners like this:my ($match) = $string =~ /$regex/;
In this context I was just bitten by the (documented) behaviour that a failed match does not reset the match variables which in my case lead to a wrong sum as on empty lines where the regex did not match the previous match was (again) added to the sum.perl -ne '/$regex/, $SUM += $1; END { print $SUM }' file.txt
For curiosity's sake now:
Assuming I did not want to introduce new variables but use $1 etc: How would I reset these variables to avoid the wrong sum as both "undef $1" as "$1=undef" does not work?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: reset of match variables
by Corion (Patriarch) on Oct 03, 2011 at 14:40 UTC | |
|
Re: reset of match variables
by choroba (Cardinal) on Oct 03, 2011 at 14:38 UTC | |
|
Re: reset of match variables
by JavaFan (Canon) on Oct 03, 2011 at 15:09 UTC | |
by AnomalousMonk (Archbishop) on Oct 03, 2011 at 22:25 UTC | |
by bart (Canon) on Oct 04, 2011 at 11:31 UTC | |
by ambrus (Abbot) on Oct 04, 2011 at 12:34 UTC | |
by hbm (Hermit) on Oct 03, 2011 at 18:22 UTC | |
by bart (Canon) on Oct 04, 2011 at 11:35 UTC |