Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Reorganising a Hash for Output

by bmcatt (Friar)
on May 07, 2002 at 13:30 UTC ( #164633=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://164633]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (1)
As of 2022-01-28 23:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (74 votes). Check out past polls.

    Notices?