Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

hash pointing to AoA

by sovixi (Novice)
on May 19, 2008 at 11:49 UTC ( [id://687359]=perlquestion: print w/replies, xml ) Need Help??

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

Is there a chance for my hash to point to AoA i.e $hash{$key} = AoA; If yes how can I do it?

Replies are listed 'Best First'.
Re: hash pointing to AoA
by ikegami (Patriarch) on May 19, 2008 at 12:08 UTC

    You can create a HoA just like you create an AoA. If the As in the HoA happen to be AoAs, that's just fine and dandy. You'll end up with a HoAoA.

    Keep in mind that you can't store an array into a hash anymore than you can store an array into an array. You can only store a reference to an array.

    my %HoAoA = ( foo => [ [ 1,2 ], [3,4] ], bar => [ [ 5,6 ], [7,8] ], ); use Data::Dumper; print Dumper \%HoAoA;
Re: hash pointing to AoA
by moritz (Cardinal) on May 19, 2008 at 11:53 UTC
    You can nest arbitrary data structures as long as you use references. See perlreftut and perldsc for more informations.
    my @aoa = ([1, 2], [3, 4]); my %hash; $hash{foo} = \@aoa;
Re: hash pointing to AoA
by mwah (Hermit) on May 19, 2008 at 13:29 UTC

    An additional (interesting?) question would be: how can I create an AoA on a hash key 'in place', for example I want to create a 10x10 boolean array that is located in a hash under a specific key, e.g.:

    # example: build a 10x10 boolean field on a hash key my $key='10x10'; my %hash; for my $row (0..9) { for my $col (0..9) { push @{ $hash{$key}[$row] }, int(rand()+0.5); } }

    Afterwards, we could run through our array by iteration over indexes:

    for my $row (0..9) { for my $col (0..9) { print "{$key} => [$row][$col] = $hash{$key}[$row][$col] \n" } }

    Regards

    mwa

      Here is a somewhat more idiomatic implementation of your code:
      use strict; my %hash; my $key='NetWallah'; $hash{$key} = [ map{ [ map {int(rand()+0.5)} 0..9 ] } 0..9 ]; printit(\%hash); sub printit{ my $href=shift; for my $key(sort keys %$href){ my $row = 0; print "{$key} =>\n"; for my $rowref (@{$href->{$key}}) { print " $row\t"; for my $val (@$rowref) { print "$val "; } $row++; print "\n"; } } }

           "How many times do I have to tell you again and again .. not to be repetitive?"

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://687359]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (2)
As of 2024-04-25 03:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found