neilwatson has asked for the wisdom of the Perl Monks concerning the following question:

Consider this:
my %hash = ( keya => [a1, b1, [ qw(c1a, c1b) ] ], keyb => [a2, b2, [ qw(c2a, c2b) ] ], )

Now the tricky part. Trying to access it. I'm close but not quite there:

foreach my $key (sort keys %hash){ print @{$hash{$key}}[0]; #prints a1 for first hash print @{$hash{$key}}[1]; #prints b1 for first hash print @{$hash{$key}}[2]; #how do I access this list? }

How do I access the last array in each hash?

Neil Watson
watson-wilson.ca

Replies are listed 'Best First'.
Re: Complex data structure
by Zaxo (Archbishop) on Oct 16, 2003 at 01:11 UTC

    In all cases you don't need to tack on the @ sigil. Your inner array simply needs another index,

    foreach my $key (sort keys %hash){ print $hash{$key}[0]; print $hash{$key}[1]; print $hash{$key}[2][0]; print $hash{$key}[2][1]; }

    After Compline,
    Zaxo

Re: Complex data structure
by fglock (Vicar) on Oct 16, 2003 at 01:11 UTC
    my %hash = ( keya => [a1, b1, [ qw(c1a c1b) ] ], keyb => [a2, b2, [ qw(c2a c2b) ] ], ); foreach my $key (sort keys %hash){ print $hash{$key}[0]; print $hash{$key}[1]; print $hash{$key}[2][0]; print $hash{$key}[2][1]; }

    note: don't use a comma inside qw() - it expects just spaces.

Re: Complex data structure
by The Mad Hatter (Priest) on Oct 16, 2003 at 01:08 UTC
    foreach my $key (sort keys %hash){ print @{$hash{$key}}[0]; #prints a1 for first hash print @{$hash{$key}}[1]; #prints b1 for first hash print @{@{$hash{$key}}[2]}[0]; #prints c2a }
    See perlref. Alternatively (and I like this syntax better),
    foreach my $key (sort keys %hash){ print $hash{$key}->[0]; print $hash{$key}->[1]; print $hash{$key}->[2]->[0]; }

      Only that first arrow is necessary. Perl does the rest of the dereferencing without being told:

      print $hash{$key}->[2][0];

      ----
      I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
      -- Schemer

      :(){ :|:&};:

      Note: All code is untested, unless otherwise stated

Re: Complex data structure
by pg (Canon) on Oct 16, 2003 at 01:10 UTC
    print $hash{"keya"}->[2][1];

    First you get to the first level array by using hash key; Secondly, that second level array ref is the 2nd element of the first level array (0-based); Eventually, use the index in the second level array to access each element in it.

    By the way, use Data::Dumper to peek into the structure, then no data structure is complex any more. To use it:

    use Data::Dumper; ... print Dumper(\%hash);
    It is also fine to say:
    print Dumper(%hash);
    But personally I don't like it, as visually you lose the feeling that you are displaying a hash.
Re: Complex data structure
by neilwatson (Priest) on Oct 16, 2003 at 01:23 UTC