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

Hi Guys,

I just have a quick question.
Is it possible to do this:

#!/usr/bin/perl -w use strict; use warnings; my %hash = (); $hash{1} = ["me","you"]; foreach my $item ( $hash{1} ) { print "$item\n"; } exit;

I can get the array back but it is as a single variable rather than an array.

Any help would be appreciated.

Cheers,
Reagen

Replies are listed 'Best First'.
Re: Perl Array Question
by Enlil (Parson) on May 15, 2004 at 08:50 UTC
    $hash{1} is a reference to an array to get the values back dereference it:
    #!/usr/bin/perl -w use strict; use warnings; my %hash ; $hash{1} = ["me","you"]; foreach my $item ( @{$hash{1}} ) { print "$item\n"; } exit;

    update:Meant to point out tye's References quick reference for further reference.

    -enlil

      Cool. Thanks for your help.
Re: Perl Array Question
by davido (Cardinal) on May 15, 2004 at 08:50 UTC
    Just rephrase your foreach loop like this, and you'll have it:

    foreach my $item ( @{$hash{1}} ) { .......

    You basically have to dereference the anonymous array ref held in $hash{1}.


    Dave

Re: Perl Array Question
by Aragorn (Curate) on May 15, 2004 at 14:29 UTC