Using Multi dimensional hashs in Perl

Networking/Security Forums -> Programming and More

Author: tutaepakiLocation: New Zealand PostPosted: Thu Nov 07, 2002 4:31 am    Post subject: Using Multi dimensional hashs in Perl
I'm writing something for a collegue in Perl in which a multi dimensional
hash would be a nice solution. But I'm buggered if I can get them to work.
I've tried to find examples etc and read the man pages etc.
What I'd like to do is create a hash like....

$HASH{$target}{$interface} = $value

whilst reading a file. I'll used the data, and change some of it, and when
I'm finished write the hash back out to the file.
I get no syntax errors, and loading the hash appears to work, but I can't
work out how to process the hash sequentially at the end. Something like

while (($key,$value) = each %HASH)

returns the value I set in $interface above as the key, and HASH{0X87AB} in value. (or some such pointer(?) )

Does anyone have a decent tutorial or example of something like this?

I'm currently working around by creating a single dimensional array like

$HASH{$target~$interace} = $value

which works fine, but I don't like relying on a special char as a separator in case it's used somewhere else.


Author: enigmanLocation: Sydney PostPosted: Thu Nov 07, 2002 5:56 am    Post subject:
As you had thought, it is a pointer (to the second hash). When you print out the first hash it contains a reference to the address containing the second hash.

The following code sample is from the excellent book Perl by Example 3rd Edition by Ellie Quigley. Probably one of the best books for learning Perl (IMO). The following code demonstrates the concept with anonymous hashes but you should be able to adapt it. Let me know if you need further assistance.

#! /usr/bin/perl
# Program to demonstrate a hash containing anonymous hashes.
my $hashref ={
   Anna => 100,
   Hao => 95,
   Rita => 85,
    Science => {
   Sam => 78,
   Lou => 100,
   Vijay =>98,
print "Anna got $hashref->{Math}->{Anna} on the Math test.\n";
print "Lou's grade was changed to $hashref->{Science}->{Lou}.\n";
print "The nested hash of Math students and grades is: ";
print %{$hashref->{Math}}, "\n"; # prints the nested hash, Math
foreach $key (keys %{$hashref}){
    print "Outer key: $key \n";
   printf "\tInner key: %-5s -- Value: %-8s\n",

Despite the high cost of living, it remains popular.

Networking/Security Forums -> Programming and More

output generated using printer-friendly topic mod, All times are GMT + 2 Hours

Page 1 of 1

Powered by phpBB 2.0.x © 2001 phpBB Group