develooper Front page | perl.beginners | Postings from April 2011

hash troubles

Thread Next
From:
dbro
Date:
April 16, 2011 01:40
Subject:
hash troubles
Message ID:
bd9d3812-3a30-4d66-a87e-40bb86e0c1cc@e8g2000vbz.googlegroups.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";
	}
}


But when I try to just print a total instead of every instance of the
words type at command prompt it seems to just hold onto just  the last
value in hash.  This what is the code:


#!/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";
}


Any help would be greatly appreciated.
Thank You


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About