From: "dbro" <devi...@gmail.com>
> Im trying to learn hashes but having a hard time trying to figure out
> why it seems I cant use data from a hash outside of the original for
> loop.  This code works as expected to me.  I guess it would be the
> same if i just stuck a print statement after the hash assignment:
> 
> 
> #!/usr/bin/perl -w
> use strict;
> our %hash;
> our @array;
> our $count;
> our $value;
> our $key;
> print "Enter data then press ctrl D:\n";
> @array = <STDIN>;
> chomp @array;
> print "@array\n";
> $count = 1;
> foreach ( sort @array ) {
> if (! $hash{$_} ) {
> %hash = ( $_ => $count );
> } else {
> $hash{$_} = $hash{$_} + 1;
> }
> while (( $key, $value ) = each %hash) {
> print "$key has been seen $value times\n";
> }
> }
> 
> 


The line:

%hash = ( $_ => $count );

re-creates a new hash each time it runs, and this program works only because 
you first sort the source array.

If the array wouldn't be sorted, and it would contain say the letters A B A B, 
it would print that A appears 1 time, B appears 1 time, A appears 1 time...

If you want to print the elements of the array (with the number they appear) in 
order, you need to do the sort in the last loop:

#!/usr/bin/perl

use strict;
use warnings;

print "Enter data then press ctrl D (or CTRL+Z+<ENTER> under Windows:\n";

my @array = <STDIN>;
chomp @array;
print "@array\n";

my %hash;

for ( @array ) {
    $hash{$_}++;
}

for my $key ( sort keys %hash ) {
    print "$key has been seen $hash{$key} times\n";
}
Octavian


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