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


in reply to Reorganising a Hash for Output

Try this...
#!/usr/bin/perl -w use strict; my %x = ( 1 => [qw(d e f)], 2 => [qw(a b c)], 3 => [qw(g h i)] ); my %rev = map { my $key=$_; map { $_=>$key} @{$x{$key}} } keys %x; print "$_ -> $rev{$_}\n" foreach sort keys %rev;

The trick (imho) is to build the "reverse" hash first and then deal with sorting / outputing that after the fact.

Btw, I'd suggest not using non-standard notation, even if it's comfortable for you. It'll (potentially) make things harder when you're trying to show other people.

Replies are listed 'Best First'.
Re: Re: Reorganising a Hash for Output
by tachyon (Chancellor) on May 07, 2002 at 15:13 UTC

    The trick (imho) is to build the "reverse" hash first

    Wrong. What if you have duplicate values in your arrays? You will loose a whole lot of values as they can't exist as "duplicate" hash keys. Oops

    my %x = ( 1 => [qw( o o p s )], 2 => [qw( j u s t )], 3 => [qw( a n o t h e r )], 4 => [qw( h a s h )], 5 => [qw( e r r o r )], 6 => [qw( j u s t a n o t h e r p e r l h a c k e r , )] ); my %rev = map { my $key=$_; map { $_=>$key} @{$x{$key}} } keys %x; print "$_ -> $rev{$_}\n" foreach sort keys %rev;

    What happened to all the values for keys 1-5?

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print