On Apr 17, 2013, at 11:17 AM, Irfan Sayed wrote:

> hi,
> need help on hashes 
> here is the code :
> 
> 
> print "Enter the words: ";
> chomp(my @words = <STDIN>);
> 
> my %names;
> 
> foreach $a (@words) {
> if (!%names) {
> print "hi\n";
> $names{$a} = 1;
> } else {
> while ( ($key, $value) = each %names ) {
> if ($a eq $key) {
> $names{$key} += 1;
> } else {
> $names{$a} = 1;
> }
> }
> }
> }
> 
> foreach ( ($key2, $value2) = each %names ) {
> print "$key2 => $value2\n";
> }
> 
> if i enter the values like a b a (separated by enter)
> then output is :
> hi
> a => 1
> a => 1
> 
> instead it shud be : 
> a => 1
> b => 1
> a =>2
> 
> please suggest 

You have made two errors:

1. You should not modify a hash while you are iterating through it with the 
each() function. The each() function uses an internal data structure that 
persists from one call of each to the next. That internal data structure can be 
modified if you add or delete elements (as you are doing). See 'perldoc -f 
each' for more information.

2. You should use while( ($key,$val) = each %names) ... and not foreach. The 
foreach is looping over the list ($key2,$value2), and each() is only getting 
called once.

Other suggestions:

1. Add use strict to your program
2. Use indenting to make your code more readable.


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