in reply to Help with hash/array data structure

References are a big spicy meatball! And, of course, there's more than one way to do it.

The following snippet might help:

use strict; my %packet_fields = ( 'Format_X' => ['ident', 'flags', 'x', 'y', 'mode3'], 'Format_Y' => ['ident', 'RDP_Ident', 'Radar_Site_Ident', 'site_x'] ); foreach my $format (keys %packet_fields) { foreach my $field (@{$packet_fields{$format}}) { #line 9 print "$format -> $field\n"; } } foreach my $format (keys %packet_fields) { print "$format's 2nd field = ", $packet_fields{$format}->[1], "\n"; +#line 15 print "$format's 3rd field = ", $packet_fields{$format}[2], "\n"; #l +ine 16 }

In this sample, %packet_fields is a regular old hash. The keys for this hash are garden-variety scalars. The value associated w/ each key is a reference to an anonymous (unnamed) array. These two anon. arrays are the only references that we have to deal with, and the only things that require any dereferencing syntax.

The @{} in line 9 is using a form of dereferencing notation to give me an array.

There's another form of dereferencing that I can use, too, as seen in lines 15 and 16.

Hanlon's Razor - "Never attribute to malice that which can be adequately explained by stupidity"

Replies are listed 'Best First'.
Re: Re: Help with hash/array data structure
by robinbowes (Beadle) on Nov 13, 2003 at 10:07 UTC
    Hi, Thanks for all the replies - most informative!

    I've now got working code, something like this:

    # Declaration of the data structure my %packet_fields = ( $Idents{ Format_7 } => [qw( ident x y flight_level chksum )], $Idents{ Rotation_Marker } => [qw( ident site_x site_y chksum )], ); # This structure listed for completeness of this example! my %packet_template = ( $Idents{ Rotation_Marker } => "C3 n n n n n n n n n n n n C3", $Idents{ Format_7 } => "C B16 n2 A4 A8 A2 A A A3 C2 +", ); # Referencing the data structure # code here to read $buffer from STDIN # $ident is extracted from $buffer @packet{ @{$packet_fields{ $ident }} } = unpack ( $packet_template{ $ident }, $buffer);
    I've got one further question about creating and accessing a hash of hashes.

    I'm currently using the following structures:

    my %ARP_GLA = ( x => 247866.9, y => 666999.7, ); my %ARP_EDI = ( x => 314382.0, y => 673841.9,
    I'd like to combine these into one data structure which I guess is a hash of hashes.

    I believe I know enough to create the hash. This should do the trick:

    my %ARP = ( GLA => { x => 247866.9, y => 666999.7 }, EDI => { x => 314382.0, y => 673841.9 } );
    How do I now access the elements in this structure?

    Is it something like:

    my $edi_arp = $ARP{EDI}->{x};
    Thanks.

    R.

    --
    Robin Bowes | http://robinbowes.com