Hash of Arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Akino877
    New Member
    • Nov 2007
    • 37

    Hash of Arrays

    Hello,

    I read in a book that I can create a hash of arrays like this :
    Code:
    %hash = ( "testA" => [77,88],
                      "testB" => [90, 91] );
    In this code, each key is associated with a reference to an array.
    My question is can I set it up so that each key is associated with
    an array - not a reference to an array?

    I have tried :
    Code:
    %hash = ("testA", (77,88),
                     "testB", (90,91) );
    But it did not work for me.

    Thank you - Akino
  • Kelicula
    Recognized Expert New Member
    • Jul 2007
    • 176

    #2
    What is the benefit? Why are you trying to make each key be associated with an array as opposed to a reference to an anonymous array?

    Comment

    • Akino877
      New Member
      • Nov 2007
      • 37

      #3
      Hi Kelicula,

      Thank you very much for your reply.

      There is no reason for me to try to do that - I was just curious.
      Now, I understand that a value in a hash can only be a scalar.

      Akino

      Comment

      • Kelicula
        Recognized Expert New Member
        • Jul 2007
        • 176

        #4
        No problem Akino877!
        The way perl overcomes this is through "references ", you can use a reference to an array or hash, or even an array of hashes or hash of arrays as a value for a hash, here's an example:
        To make a reference you simply use the slash like so:
        my @array = ('Jon', 'James', "jimmy', 'Julie');
        my $array_ref = \@array;

        Now $array_ref is a scalar value that points to the memory allocation spot of the array named @array.

        Or you can just make a reference initially with the square brackets:

        my $array = ['Jon', 'James', 'jimmy', 'Julie'];

        Then
        my %hash = ( one => $array, two => $array2, etc... );

        To make a reference to an anonymous hash you can use the "{" like so:

        my $hash_ref = { one => $array_ref, two => $array_ref2, etc..};

        You access these references with the special arrow operator:
        $hash->{one}->[1] would equal "James".

        Data structures can be very complicated and deep in Perl, but it's all accomplished through references, there are really only 4 types of values in perl; scalar, hash, array, or TYPEGLOB.

        There's WAY to much about this to include here, but that should give you some terms to Google with ;-)

        Here is a great place to start:


        Happy coding...
        Last edited by Kelicula; Jan 26 '15, 06:41 PM. Reason: Adding URL to perlref

        Comment

        Working...