Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

reset of match variables

by morgon (Deacon)
on Oct 03, 2011 at 14:29 UTC ( #929350=perlquestion: print w/ replies, xml ) Need Help??
morgon has asked for the wisdom of the Perl Monks concerning the following question:

Hi

in scripts I usually match like this:

my ($match) = $string =~ /$regex/;
but sometimes I do one-liners like this:
perl -ne '/$regex/, $SUM += $1; END { print $SUM }' file.txt
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.

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?

Comment on reset of match variables
Select or Download Code
Re: reset of match variables
by choroba (Abbot) on Oct 03, 2011 at 14:38 UTC
    Just use /$regex/ and $SUM += $1
Re: reset of match variables
by Corion (Pope) on Oct 03, 2011 at 14:40 UTC

    You can't reset them without doing a new match, but you can easily check whether there was a match:

    perl -ne '/$regex/ and $SUM += $1; END { print $SUM }' file.txt
Re: reset of match variables
by JavaFan (Canon) on Oct 03, 2011 at 15:09 UTC
    Untested:
    $SUM += /$regex/ && $1; # Don't turn on warnings.

      Or even just this:

      $SUM += /$regex/;

      Update: Sorry, mine only counts the number of matches (like grep -c). To accumulate the values of matches, I still instinctively reach for (something like) this:

      nawk '/([0-9]*)/{tot+=$1}END{print tot}' file

      With warnings and strictures:

      >perl -wMstrict -lne "$::SUM += /(\d+)/ && $1; END { print $::SUM } " foo123bar foo xxx111ccc xxx ^Z 234
        Jeezes, who would want to use strict and a workaround for a one-liner??
      Warnings do nothing: if the regexp fails then it'll return false, which is 0 when treated as a number, not undef, and without a warning.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://929350]
Approved by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (15)
As of 2014-09-23 12:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (220 votes), past polls