in reply to Re: Array of Arrays with Variable Names
in thread Array of Arrays with Variable Names

This reply apples to at least two of the above entries, the third I haven't had a chance to address. All of the data is being pulled in from a file of the following structure:
@array1=( 'entry1', 'entry2', ... ); @array2=( 'entry1', 'entry2, ... ) ...
There are a few rules I have to follow here: 1. I can not modify the format of the data file - it is not static, nor do I 'own' it where I can change the way it's generated. 2. The arrays can not be in the script itself . I guess the whole question boils down to this, how can I have the following:
@combined = ( $opt_f );
..interpret the following:
$opt_f = '@array1,@array2'
As a list of arrays which are then combined, and not simply treat them as regular entries, strings "@array1", "@array2"?

Replies are listed 'Best First'.
Re^3: Array of Arrays with Variable Names
by mreece (Friar) on Aug 25, 2006 at 17:39 UTC
    if you absolutely must do it this way, here is how (use eval):
    ## this is an example, works just as well if these arrays come from a +require'd file my @array1 = qw(a b c); my @array2 = qw(d e f); ## again, just an example, works just as well if this comes from GetOp +t my $opt_f = '@array1, @array2'; ## here is the magical and evil eval my @combined = eval "$opt_f"; print "@combined\n";
      AHA! Thanks, mreece (and others). That's what I'm looking for - and it's working now. From that suggestion, I've constructed the following snippet which is just a small portion of a much larger work:
      #!/usr/local/bin/perl5 -w use Getopt::Std; require "/path/datafile"; getopts('f:'); chomp $opt_f ; if ( $opt_f ) { @combined = eval "$opt_f" ; } foreach $entry ( @combined ) { print "$entry \n"; }
      Thanks for your patience with a beginner. I read through the warnings about variables in array names before I posted the original post, so I was expecting a lot of people to jump onto that detail... thanks for taking the time to fully understand the problem.
        one last thing, which i should have mentioned in my previous post. you should check the $@ variable for errors following the eval. consider something like:
        @combined = eval "$opt_f" ; if ($@) { die "could not construct a combined array from '$opt_f': $@"; }

      mreece++ (similarly wojtyk below)... at least if we've correctly interpreted the OP's requirements.

      However, since the OP explicitly requested an Array of Arrays, I'd modify the code somewhat (and add a minimum of error checking):

      # Dummy stuff for testing: my @array1 = qw ( a b c ); my @array2 = qw ( d e f ); my @et_cetera = qw ( etc etc etc ); my $opt_f = '@array1,@array2,@et_cetera'; my @AoA; for ( split /,/, $opt_f ) { my $array_ref = eval '\\' . $_; die "Bad input: '$_' doesn't seem to exist!\n" if $@; push @AoA, $array_ref; } print "@$_\n" for @AoA;