Front page | perl.beginners |
Postings from February 2002
Re: Hash Question
Thread Previous
|
Thread Next
From:
Chas Owens
Date:
February 1, 2002 10:25
Subject:
Re: Hash Question
Message ID:
1012587961.15605.37.camel@tert.icallinc.com
On Fri, 2002-02-01 at 12:42, Balint, Jess wrote:
> Since this is a beginners list, I thought I would be allowed to ask this
> question. Can there be multiple values for hash keys, or just one? The
> reason I am asking is that I am working on a statistical program and would
> need to use multiple hashes as values of another hash. If this is possible,
> please let me know. Thank you.
>
> -Jess
>
I assume you mean a multi-dimensional hash. Perl allows infinite
(assuming you have the resources) nesting of data structures. This is
accomplished by using a reference to the structure to be nested. So for
a three dimension hash you would first have a hash whose values were
hash references. Then those hashes would have values that were also
references to hashes. You could then access the data like this:
print $hash{'key1'}->{'key2'}->{'key3'}, "\n";
but Perl being what it is provides a little syntatic suger and lets you
just write this:
print $hash{'key1'}{'key2'}{'key3'}, "\n";
<example>
#!/usr/bin/perl -w
use strict;
my %hash;
while (<>) {
my ($key1, $key2, $key3, $data) = split;
$hash{$key1}{$key2}{$key3} = $data if $key1 and $key2 and $key3;
}
foreach my $key1 (sort keys %hash) {
foreach my $key2 (sort keys %{$hash{$key1}}) {
foreach my $key3 (sort keys %{$hash{$key1}{$key2}}) {
print "($key1)+($key2)+($key3) returns ",
$hash{$key1}{$key2}{$key3}, "\n";
}
}
}
</example>
--
Today is Boomtime the 32nd day of Chaos in the YOLD 3168
Or is it?
Missle Address: 33:48:3.521N 84:23:34.786W
Thread Previous
|
Thread Next