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

Hi, I don't know, so could you tell me, Can we insert value of array in hashref?

my @array = ('test', 'demo', 'work'); #hashref my $value = { 'key' => ['value' , @array , 'add']; }

Is it possible? If no then any other way to insert an array in hashref?

Replies are listed 'Best First'.
Re: Can i stored an array in hashref?
by moritz (Cardinal) on Nov 26, 2009 at 07:38 UTC

    You can. The way you showed it flattens the array, if you don't want that, put a reference to it in your data structure:

    my $value = { 'key' => ['value', \@array, 'add']; }

    See also: perllol, perldsc, perlreftut.

    Perl 6 - links to (nearly) everything that is Perl 6.
      I like the way that moritz answered. The answer will work great for this specific single question! But I am not sure that the answer will help you in your application.

      my @array = ('test', 'demo', 'work'); my $value = { 'key' => ['value', \@array, 'add']; }
      This puts a reference to @array as the 2nd thing in the anon list that 'key' points to. If the contents of @array can vary and in real application, I presume that it will, then,
      'key' => ['value', [@array], 'add'];
      The above says that I am going to make copy of @array, and then assign a reference to that in this key structure. That is different than assigning a ref to the @array.

Re: Can i stored an array in hashref?
by AnomalousMonk (Archbishop) on Nov 26, 2009 at 17:09 UTC
    Is it possible?
    Why not try it and see?
    >perl -wMstrict -le "use Data::Dumper; my @array = qw(test demo work); my $value = { 'key' => ['value', @array, 'add'] }; print Dumper $value; " $VAR1 = { 'key' => [ 'value', 'test', 'demo', 'work', 'add' ] };
Re: Can i stored an array in hashref?
by biohisham (Priest) on Nov 26, 2009 at 15:11 UTC
    While reading your post I assumed @array can be of varying length, so there maybe a need for such a provision to be held. In addition to the informative replies you received, I thought I would just demonstrate this in an example which shows the possibility of array manipulations on @array while it is in $hashref... this is just an example:
    use Data::Dumper; my @array = ('test', 'demo', 'work'); my $hashref = {'key'=>['value', [@array], 'add']}; push @{$hashref->{'key'}->[1]}, 'home'; push @{$hashref->{'key'}->[1]}, 'cars'; printf "I popped \'%s\'.\n\n", pop @{$hashref->{'key'}->[1]}; print Dumper(\%$hashref);


    Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind.