Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

counter for each regex match.

by tty1x (Novice)
on May 04, 2013 at 05:57 UTC ( [id://1031991]=perlquestion: print w/replies, xml ) Need Help??

tty1x has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to increase the $count variable by 1 whenever any line in the opened file contains the word Mailto:

However, I kept receiving use of uninitialised value $count error and a long string of numbers at the end as the result.

my @email = <OPENFILE>; close OPENFILE; my $count; foreach my $email (@email){ if ($email =~ /mailto:/) { $count += 1; } print $count; # error here }

Replies are listed 'Best First'.
Re: counter for each regex match.
by davido (Cardinal) on May 04, 2013 at 06:05 UTC

    $count's initial state is "undef", or undefined. It doesn't get incremented until the first time that "mailto:" shows up in your input file. Yet you print its value on each iteration.

    So imagine the first line of your file is, "More pizza please!". The regex obviously won't match, and so $count won't be incremented. So when you print $count's value, it is still 'undef'.

    Either initialize it with a value right where you're declaring $count, or move it outside of the foreach loop, or put an "if defined $count" suffix at the end of your print statement.


    Dave

      Thanks for the explanation. Moving the print statement out of the for loop did the trick. Elementary mistake =/
Re: counter for each regex match.
by Laurent_R (Canon) on May 04, 2013 at 08:16 UTC

    However, I kept receiving use of uninitialized value $count error and a long string of numbers at the end as the result.

    From your own description of the problem, the main point is to move the print statement outside of the while loop, so that it gets executed only once after you have finished looping on the input.

    Initializing $count to 0 when you declare it is slightly less important, but it will avoid the "uninitialized value" warning in the case where nothing was matched in your while loop.

Re: counter for each regex match.
by kcott (Archbishop) on May 04, 2013 at 10:45 UTC

    G'day tty1x,

    Changing my $count; to my $count = 0; should fix your "uninitialised value" problems.

    [Aside: you can write ++$count; instead of $count += 1;]

    -- Ken

      Thanks for the  ++$count; tip :)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2024-04-24 11:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found