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

This is probably a quite easy question for some, but it is just eluding me. I have a hash. Each element of the hash is a list of values. I need to move those values into an array.

This does not work:

$Hash{"Element"}='A B C D E'; my @Array=$Hash{"Element"}; #Probably syntax problem here. print "$Array[0]\n"; #expecting 'A' getting 'A B C D E'

Suggestions, Oh Wise ones?

Skip

Replies are listed 'Best First'.
Re: Copying a hash element into an array as a list
by Roy Johnson (Monsignor) on Mar 24, 2004 at 17:35 UTC
    What you've got is not a list in the Perl sense, but a string. You need to use split to turn it into a list, so you can assign it to an array sensibly:
    my @Array = split ' ', $Hash{'Element'};

    The PerlMonk tr/// Advocate
Re: Copying a hash element into an array as a list
by bassplayer (Monsignor) on Mar 24, 2004 at 17:34 UTC
    Change the second line to:

    my @Array=split /\s/,$Hash{"Element"};

    This splits the string on spaces before sending it to the array.

    bassplayer

Re: Copying a hash element into an array as a list
by Happy-the-monk (Canon) on Mar 24, 2004 at 17:54 UTC

    The monks have provided a suitable solution to your problem. However, if you could just change the base of the problem a bit, then make it

    $hash{'element'} = [ "A".."E" ]; # reference to anonymous array contai +ning A-E. my @array = @{ $hash{'element'} }; # dereference and copy the array in +to @array. print "$array[0]\n", $hash{'element'}->[0], "\n";

      Yes, the monks did provide what I need. I considered using a hash reference, but I use that same hash natively several other places, just here I need to treat its contents as an array.

      Thank you and the other monks!

        I considered using a hash reference ...

        You mean array reference, right? The reference isn't to what's holding it, it's to what's being held.

        ------
        We are the carpenters and bricklayers of the Information Age.

        Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose