BlenderHead has asked for the wisdom of the Perl Monks concerning the following question:

Hello World:

I have the following code written to generate a hash:

my $count = 1; my @array = ('A','B','C'); my %hash = (); for my $i (@array) { # set key AND initialize by $count as value of key. $hash{$i} = $count; $count++; }

Now, what I want to do is sort the hash by values and print it out, but my print loop isnt working right. I can get the values out okay, but the keys are not working to print.

Here's what I have.

for my $key ( sort {$hash{$a} <=> $hash{$b} } keys %hash ) { print " MIRACLE_HAPPENS is equal to $hash{$key}.<br>\n"; }

As you can see - it wont print the key name. It'll only print the sorted values. Where it says "MIRACLE HAPPENS" is where I need it to print the key name. Can anyone show me how to do that please?

Thanks!

BH

Replies are listed 'Best First'.
Re: Simple Hash Question
by kennethk (Abbot) on Nov 18, 2009 at 21:52 UTC
    The keys of the hash are what you want to print out. If I understand your difficulty, all you need to do to get your desired result it to use $key in place of $hash{$key} in your print statement, i.e.

    #!/usr/bin/perl use strict; use warnings; my $count = 1; my @array = ('A','B','C'); my %hash = (); for my $i (@array) { # set key AND initialize by $count as value of key. $hash{$i} = $count; $count++; } for my $key ( sort {$hash{$a} <=> $hash{$b} } keys %hash ) { print " MIRACLE_HAPPENS is equal to $key.<br>\n"; }
Re: Simple Hash Question
by BioLion (Curate) on Nov 18, 2009 at 21:56 UTC

    Not sure if I am missing something, but if you want to print the key, print the key:

    for my $key ( sort {$hash{$a} <=> $hash{$b} } keys %hash ) { print " MIRACLE_HAPPENS is equal to key : \'$key\' and value : \' +$hash{$key}\'.\n"; }

    perldoc may be a good resource for further reading. HTH.

    Just a something something...

      A minor point but you don't have to escape single-quotes in a double-quoted string.

      $ cat xxx $key = 'abc'; print "Key is: '$key'\n"; $ perl xxx Key is: 'abc' $

      I hope this is useful.

      Cheers,

      JohnGG

      Heh... Am sorry guys...

      Thank you for your help. :) It solved the problem.

      As per reading the manual - I AM reading the manual... I wouldn't be here if I weren't... ;-)

Re: Simple Hash Question
by ikegami (Patriarch) on Nov 18, 2009 at 22:12 UTC
    If you're trying to count the number of occurrences of each array element, what you want is:
    my @array = qw( a b r a c a d a b r a ); my %counts; ++$counts{$_} for @array; for my $key ( sort { {$counts{$b} <=> $counts{$a} } keys %counts ) { print("$key: $counts{$key}\n"); }