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

Is it possible to assign a array reference as a value to a hash key ? If yes, then how to assign it to a hash key ?

Thanks

  • Comment on Is it possible to assign an array reference to a value in hash

Replies are listed 'Best First'.
Re: Is it possible to assign an array reference to a value in hash
by stevieb (Canon) on May 14, 2012 at 23:13 UTC
    my @array = qw(a b c); my %hash; $hash{ key } = \@array;

      Or alternatively:

      my %hash = ( foo => [ 'bar', 'baz', 'qux' ], anything => [ 'else', 'you', 'want', 'to', 'include' ] );
      Either way works, your choice.

      ~Thomas~ I believe that the source code to life is written in Perl :-)
Re: Is it possible to assign an array reference to a value in hash
by Anonymous Monk on May 14, 2012 at 23:13 UTC

    See perlref and Modern Perl

    Making References References can be created in several ways. 1. By using the backslash operator on a variable, subroutine, or valu +e. (This works much like the & (address-of) operator in C.) This typically creates *another* reference to a variable, because there +'s already a reference to the variable in the symbol table. But the symbol table reference might go away, and you'll still have the reference that the backslash returned. Here are some examples: $scalarref = \$foo; $arrayref = \@ARGV; $hashref = \%ENV; $coderef = \&handler; $globref = \*foo;
Re: Is it possible to assign an array reference to a value in hash
by sauoq (Abbot) on May 15, 2012 at 01:02 UTC
    Is it possible to assign a array reference as a value to a hash key ?

    You can use array references as keys in just the way you might guess that you can... the limitation is that you can't retrieve the key and then dereference it. This is because hash keys are strings by definition and when you use a reference as a key, it stringifies the reference first.

    You probably want Tie::Refhash to do what you want to do.

    -sauoq
    "My two cents aren't worth a dime.";

      I am talking about the "value" to a hash key not key as an array reference.

      I am able to deference the value when I use it as an array reference. Thanks for the suggestions.

        It is unclear whether you consider your (updated) question answered.

        To complete stevieb's example, you can retrieve a value thusly:

        my $retrieve = $hash{ key } -> [1] ; # returns "b" (The "->" is opti +onal)

                     I hope life isn't a big joke, because I don't get it.
                           -SNL