develooper Front page | perl.beginners | Postings from August 2009

Re: Inverting a hash safely

Thread Previous | Thread Next
From:
Shawn H. Corey
Date:
August 3, 2009 15:44
Subject:
Re: Inverting a hash safely
Message ID:
4A776823.9070902@gmail.com
Jenda Krynicky wrote:
> And if you feel like it, create a function that reverses
> 
>  (a => 1, b => 3, c => 1) => (1 => ['a','c'], 2 => ['b'])
> 
> That's something that's not a SIMPLE oneliner. Even though of course 
> it's not too complex either.

I think it's simple enough:

#!/usr/bin/perl

use strict;
use warnings;


use Data::Dumper;
# Make Data::Dumper pretty
$Data::Dumper::Sortkeys = 1; # ASCII sort hash keys
$Data::Dumper::Indent   = 1; # first style, not indent 1 space
$Data::Dumper::Maxdepth = 0; # limits depth of output, zero == infinite

my %h = (a => 1, b => 3, c => 1);
my %r = ();

push @{ $r{$h{$_}} }, $_ for keys %h;   # one line :)

print Dumper \%h, \%r;


-- 
Just my 0.00000002 million dollars worth,
   Shawn

Programming is as much about organization and communication
as it is about coding.

My favourite four-letter word is "Done!"

Thread Previous | 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