Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

reset of match variables

by morgon (Curate)
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:


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?

Replies are listed 'Best First'.
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 choroba (Bishop) on Oct 03, 2011 at 14:38 UTC
    Just use /$regex/ and $SUM += $1
Re: reset of match variables
by JavaFan (Canon) on Oct 03, 2011 at 15:09 UTC
    $SUM += /$regex/ && $1; # Don't turn on warnings.

      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??

      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
      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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://929350]
Approved by moritz
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2018-05-23 19:04 GMT
Find Nodes?
    Voting Booth?