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

Hi, Can i Have an array as hash key?

Replies are listed 'Best First'.
Re: hash key
by Fletch (Bishop) on Jul 07, 2009 at 14:37 UTC

    Maybe, if you can live with using Tie::RefHash.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: hash key
by dreadpiratepeter (Priest) on Jul 07, 2009 at 14:37 UTC
    I can't think of any good reason why you would want that. Perhaps you could explain what you are trying to achieve and we can make suggestions as to the best way to go about it?
    incidently, Using an array as a hash key will result in a key that is the number of elements in the array. ie:
    my @a=(3,4,5); my %h; $h{@a}='fred'; print keys %h;
    will print 3


    -pete
    "Worry is like a rocking chair. It gives you something to do, but it doesn't get you anywhere."
Re: hash key
by jethro (Monsignor) on Jul 07, 2009 at 14:38 UTC

    No and yes. You can't directly, but after concatenation (in most cases with a delimiter that should not occur in the string representation of your array) you have a string again that could be used as hash key

Re: hash key
by davorg (Chancellor) on Jul 07, 2009 at 14:45 UTC

    Not really - as others have explained.

    If you told why you think you want to do that, then perhaps we could tell you a better way to achieve your goal.

    --

    See the Copyright notice on my home node.

    Perl training courses

Re: hash key
by JavaFan (Canon) on Jul 07, 2009 at 14:50 UTC
    No, but you can join all the elements into a key, or use the reference as a key (but beware of threads). Depending on why you want to use arrays as keys, it's likely either of them will do.
Re: hash key
by mscharrer (Hermit) on Jul 07, 2009 at 14:52 UTC
    You could use the array address/reference (in string form) as key. It can be questioned if this is really useful, because another array with identical content results in an different reference and therefore different key:
    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @a = (1,2,3); my %h; $h{\@a} = "value"; my @b = @a; $h{\@b} = "other value"; print Dumper \%h; __END__ $VAR1 = { 'ARRAY(0x84df0e0)' => 'other value', 'ARRAY(0x847c540)' => 'value' };
    Like other posts pointed out: You could create a string from the array (like join "\0", @array) and use this as key or maybe use a Tie package. But this all depends on what you really want to do.
Re: hash key
by bichonfrise74 (Vicar) on Jul 07, 2009 at 22:48 UTC
    Try this...
    #!/usr/bin/perl use strict; use Data::Dumper; my @array = qw( a b c ); my %hash = map { $_ => 1 } @array; print Dumper \%hash;