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

I have a string that contains the value of the variable name of an array...
@list1 = ("one","two","three","four"); @list2 = ("four","three","two","one"); $name = "list1";
Is there a quick way to reference the array given the string? (Assume there are multiple arrays and the sting can contain the name of any of them...) I can fairly easlily do an 'if' check and then utilize a reference to the array based on a match, but it seems like there should be a more direct way of accessing the array. The following works just fine, but isn't very elegant:
@list1 = ("one","two","three","four"); @list2 = ("four","three","two","one"); $name = "list1"; if ($name eq "list1") { $list_ref = \@list1; } elsif ($name eq "list2") { $list_ref = \@list2; } foreach $item (@{$list_ref}) { print "$item\n"; }

Replies are listed 'Best First'.
Re: Array name contained within a string
by Zaxo (Archbishop) on Jun 20, 2007 at 15:35 UTC

    Wrap your data in a hash:

    my %list = { list1 => ["one","two","three","four"], list2 => ["four","three","two","one"] ); my $list_ref = $list{$name};
    Your intent could also be satisfied with a symbolic reference dereference, but that would be too dirty. Just so you recognise dirt when you see it,
    my $list_ref = \@{$name};

    After Compline,
    Zaxo

Re: Array name contained within a string
by ForgotPasswordAgain (Vicar) on Jun 20, 2007 at 15:29 UTC
    You want to use a hash:
    my %lists = ( list1 => [("one","two","three","four")], list1 => [("four","three","two","one")], ); my $list_ref = $lists{$name}; ....

    You can also use symbolic references, $list_ref = \@{"list1"}, but that's ugly.

Re: Array name contained within a string
by FunkyMonk (Bishop) on Jun 20, 2007 at 16:25 UTC
    Similar to other responses, but this one lets you work with your original arrays:

    my @list1 = ("one","two","three","four"); my @list2 = ("four","three","two","one"); my %lookup = ( list1 => \@list1, list2 => \@list2 ); my $name = "list1"; print "$_\n" for @{ $lookup{$name} };