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

Re: Inverting a hash safely

Thread Previous | Thread Next
From:
Jenda Krynicky
Date:
August 3, 2009 16:41
Subject:
Re: Inverting a hash safely
Message ID:
4A779197.27479.16241C3B@Jenda.Krynicky.cz
From: "Shawn H. Corey" <shawnhcorey@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 :)

Is it simple enough so that you immediately know what does it do? I 
guess not. IMHO it's complex enough to warrant being moved to a named 
subroutine. Especially since it forces you to write the name of the 
original hash twice.

Jenda
===== Jenda@Krynicky.cz === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
	-- Terry Pratchett in Sourcery


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