http://www.perlmonks.org?node_id=562925

kwaping has asked for the wisdom of the Perl Monks concerning the following question: (sorting)

How do I print the values of a hash, sorted by the hash keys?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I print the values of a hash, sorted by the hash keys?
by Russ (Deacon) on Jan 12, 2007 at 19:39 UTC
    There's more than one way to do it.

    Here's the obvious way:

    foreach my $key ( sort keys %data ) { print $data{$key}; }

    Here it is, using a map within a single print call:

    print map { $data{$_} } sort keys %data;

    Here's a way using a hash slice:

    foreach my $val ( @data{ sort keys %data } ) { print $val; }

    Even the slice can be printed in a single print call:

    print @data{ sort keys %data };

    Of course, you'll want to set up the variables $, and $\ appropriately...

Re: How do I print the values of a hash, sorted by the hash keys?
by Tux (Canon) on Jan 13, 2007 at 20:22 UTC

    A rather obscure alternative could be

    use Data::Dumper; $Data::Dumper::Sortkeys = 1; print Dumper \%hash;

Re: How do I print the values of a hash, sorted by the hash keys?
by kwaping (Priest) on Jul 21, 2006 at 19:41 UTC
    my %data = (1 => 'c', 2 => 'b', 3 => 'a'); foreach my $val (@data{sort keys %data}) { print $val . $/; }

    Originally posted as a Categorized Answer.

Re: How do I print the values of a hash, sorted by the hash keys?
by kwaping (Priest) on Jul 21, 2006 at 19:51 UTC
    You can also do this:
    foreach my $key (sort keys %data) { print $data{$key} . $/; }
    However, my first answer works well with a join():
    print join('|', @data{sort keys %data});

    Originally posted as a Categorized Answer.

Re: How do I print the values of a hash, sorted by the hash keys?
by jacques (Priest) on Jul 22, 2006 at 13:47 UTC
    print map{ $data{$_} } sort{ $a <=> $b } keys %data;

    Originally posted as a Categorized Answer.

Re: How do I print the values of a hash, sorted by the hash keys?
by abubacker (Pilgrim) on Aug 13, 2009 at 13:04 UTC

    This is also one of the ways of achieving it

    foreach $key ( sort { $a <=> $b } keys %hash){ $star = ($hash{$key}*15)/$max ; print " Kesy and values $key\t=>\t $hash{$key}:\t", "*"x$ +star, "\n "; }

    Originally posted as a Categorized Answer.