On Mon, Jun 30, 2014 at 11:57 AM, Sunita Pradhan
<sunita.pradhan.2...@hotmail.com> wrote:
> Hi
>
> I want to count number of occurrences of one word in a line within one
> single line of perl script .
>
> My code :
>
> $c++ if ($line =~ /\s+$w\s+/g);
> print "count $c\n";
>
>
> It always return one even if $line contains same word twice . It does not do
> the global match.
> It works if I split the line but I want it in one line .
>
>

In this case, perl always returns one if there's a match due to the
boolean scalar context.
With a match the return will be 1; otherwise 0. See the docs for a
discussion of context,
 eg, perldoc perldata.

You could alter context, ie, change "if" to "while", to get the correct count:

       $c++ while $line =~ /\s\w+\s/g;

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to