On 6 July 2014 02:31, Sunita Pradhan <sunita.pradhan.2...@hotmail.com>
wrote:

> I have a set of code for count number of lines and number of words .
>
> #!/usr/bin/perl
>
> while ($line =  <STDIN>){
>         chomp ($line);
>         $hash{L_c_start}++ if ($line =~ /^C.*/i);
>         @words = split /\s+/,$line;
>         *foreach $c (keys @words){*
>                print "word $words[$c]\n";
>                $hash{W_c_start}++ if ($words[$c] =~ /^C.*/i);
>         }
> }
>
> print "$_ :: $hash{$_}\n" foreach (keys %hash);
> =========================================
>
> I want to use "while" loop instead of "foreach" . I tried it but while
> loop does not select  2nd line of <STDIN> .
>



"I tried it but while loop does not select  2nd line of <STDIN> ."

Can you show us the code after you tried that?

Why do you want to use a while loop instead of foreach?

Remember:

>  while(  condition ) {  }

Executes the condition on each iteration, so using

> while( keys @words ) { }

means the loop will continue as long as @words returns a non-zero number of
keys.

This is different from

> for my $i ( keys @words ) { }

Where the code will be evaluated once, and the result iterated.

Though I'm not entirely understanding why you've used the unusual

>        *foreach $c (keys @words){*
>               print "word $words[$c]\n";
>               $hash{W_c_start}++ if ($words[$c] =~ /^C.*/i);
>        }

Instead of the more natural

>        *foreach my $word (@words){*
>               print "word $word\n";
>               $hash{W_c_start}++ if ($word =~ /^C.*/i);
>        }


Personally, I'd be inclined to structure code as follows if a while loop
was really wanted:

>        while( @words ){
>               my ($word) = shift @words;
>               print "word $word\n";
>               $hash{W_c_start}++ if ($word =~ /^C.*/i);
>        }

And of course, standard recommendation: your code lacked 'use strict' and
'use warnings', and both are highly recommended.

-- 
Kentnl

Reply via email to