proper use of hash of hashes?

D

Dan Jacobson

This program does what I want, but is it a proper use of a hash of
hashes, etc.?
$ cat data
5a m g t
4g k x
5a t c
$ perl p.pl < data
4g: k x
5a: c g m t
$ cat p.pl
use strict;
use warnings;
my %k;
while (<>) {
my @F = split;
my $h = shift @F;
for (@F) { $k{$h}{$_} = undef }
}
for ( keys %k ) { printf "$_: %s\n", join " ", sort keys %{ $k{$_} } }
 
F

Fabian Pilkowski

* Dan Jacobson said:
This program does what I want, but is it a proper use of a hash of
hashes, etc.?

Yes, you're using all your hashes to eliminate duplicates: The outer
hash to summarize your input lines, and the inner hashes to guarantee
each character exists therein only once.
use strict;
use warnings;
my %k;
while (<>) {
my @F = split;
my $h = shift @F;

You could do this in just one line.

my( $h, @F ) = split;
for (@F) { $k{$h}{$_} = undef }

Less parantheses provides more readability, IMHO.

$k{$h}{$_} = undef for @F;

Alternatively, you could doing a hash slice here:

@{ $k{$h} }{ @F } = ();
}
for ( keys %k ) { printf "$_: %s\n", join " ", sort keys %{ $k{$_} } }

regards,
fabian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top