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

How would I iterate though this data structure and print the contents of the array?
use warnings; use strict; my %data = (); my $string = 'flinstones,fred,barney,willma,betty'; my @tmp = split(/\s*,\s*/, $string); my $key = shift @tmp; push @{$data{$key}}, [@tmp]; use Data::Dumper; print Dumper(%data);

Thanks

Replies are listed 'Best First'.
Re: printing data structure
by ikegami (Patriarch) on Jan 08, 2007 at 19:49 UTC

    hash → key: given name, value: family
    family → reference to array of given names

    foreach my $surname (keys %data) { my $family = $data{$surname}; foreach my $given (@$family) { print("$given $surname\n"); } }

    Giving meaningful names helps. Creating variables in order to use meaninful names helps. $key, $value and @tmp are bad names.

    By the way, when using Dumper, it's best if you pass a scalar. print Dumper(\%data);

      hmmm...I'm still getting the arrayref when using this:
      ... use Data::Dumper; print Dumper(\%data); foreach my $surname (keys %data) { my $family = $data{$surname}; foreach my $given (@$family) { print("$given $surname\n"); } }
      Produces:
      $VAR1 = { 'flinstones' => [ [ 'fred', 'barney', 'willma', 'betty' ] ] }; ARRAY(0x2254d8) flinstones
      Am I missing something?

        Are you sure you want
        push @{$data{$key}}, [@tmp];
        I thought you did
        push @{$data{$key}}, @tmp;

        If you really do want
        push @{$data{$key}}, [@tmp];
        what's the extra level represent?
        Names help.

Re: printing data structure
by planetscape (Chancellor) on Jan 09, 2007 at 08:56 UTC
Re: printing data structure
by siva kumar (Pilgrim) on Jan 09, 2007 at 07:29 UTC
    Try this.
    use warnings; use strict; my %data = (); my $str1 = 'flinstones,fred,barney,willma,betty'; my $str2 = 'flinstones1,fred1,barney1,willma1,betty1'; my @tmp1 = split(/,/, $str1); my @tmp2 = split(/,/, $str2); my $key1 = shift @tmp1; my $key2 = shift @tmp2; push(@{$data{$key1}} , @tmp1); push(@{$data{$key2}} , @tmp2); foreach my $key (keys %data){ foreach (@{$data{$key}} ) { print "$key - $_ \n"; } }
    Output:
    -------
    flinstones1 - fred1
    flinstones1 - barney1
    flinstones1 - willma1
    flinstones1 - betty1
    flinstones - fred
    flinstones - barney
    flinstones - willma
    flinstones - betty
    --
    Sivakumar