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

Can someone help me out with a simple question.
I have a routine that that goes through an array and processes each item. However I want that array to be variable.
Example


my (@foo, @tooarray, @mooarray, @booarray, $i);
$i = boo;
@foo = @$i.array;


so that @foo loads up the values in @booarray.
I can't seem to figure out the syntax for this. I am beginner in perl so any help would be appreciated.
  • Comment on Dynamically Assigning 1 array to another

Replies are listed 'Best First'.
Re: Dynamically Assigning 1 array to another
by Fletch (Bishop) on Nov 05, 2010 at 21:23 UTC

    You think you do, but you really want a hash of arrays. Read perlreftut and then see perldsc.

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

      OK. So I'm having some problems with dereferencing.
      I am trying to iterate through the items with this..


      foreach my $servers (@{$masterlist{$servtype}}){
      print "Let's see $servers \n";
      print RESULT " members $servers".":$serviceport\n";
      }


      When $servtype is explicitly defined it works fine, at least for that array. But when I put $servtype in there it doesn't work.
      The $servtype variable has the same values as the array name. It SHOULD work but I must be dereferencing something improperly.
        #! /usr/bin/env perl use strict; use warnings; my %masterlist = ( foo => [ 1, 2, 3, ], bar => [ 'a', 'b', 'c', ], ); my $servtype = 'bar'; for my $servers (@{$masterlist{$servtype}}) { print "$servers\n"; }
        Output:
        a b c
        Sorry I don't understand ... could you please elaborate what your problem is?

        Cheers Rolf

      I hadn't thought of that. Yeah that makes more sense. Thanks!
Re: Dynamically Assigning 1 array to another
by LanX (Saint) on Nov 05, 2010 at 21:26 UTC
    You can use a hash of arrays:
    my %HoA=( too => [...], moo => [...], boo => [...], ); my $i="boo"; my @foo=@{$HoA{$i}};
    (untested)

    Cheers Rolf