Perl: Incrementing Variable Names in a Loop?

Is it possible to increment the name of a variable (an array) within a for or foreach loop in standard Perl (not PHP)?

I want to be able to put data from each iteration of the loop in an array with a different name (e.g. @results0 for the first iteration, @results1 for the second iteration and so on).
I have discussed this with a couple of colleagues and they disagree on whether it is possible (neither of them is particularly experienced in Perl, and neither could explain how it would be done if it could).

Maybe use a multi-dimensional array?

http://www.suite101.com/article.cfm/perl/94552

To answer your question more directly, I don’t think you can create dynamic variable names with Perl. Creating a multi-dimensional array can serve the same purpose though.

Never, ever do this. It’s possible, but involves the use of symbolic references, which leads to all sorts of problems. The correct procedure is to simply use a two-dimensional array. E.g.

$results[$counter] = [ 1, 2, 3, 4 ];

or

$results[$counter] = @array;

Why symbolic references are bad.

You can, but if you do, I’ll come over to your house and punch you.

What Friedo said. You can dynamically create variable names but it’s such a stupid idea that I refuse to be part of it. The multi-dimensional array facility does excactly what you want, and it’s designed with exactly that purpose in mind.

LOL.

I’ve never used a two-dimensional array before though. Are there any pitfalls I need to watch out for in the implementation?

Just remember that in Perl, complex data structures are built with references. Square brackets construct an anonymous array reference, and a backslash takes a reference to a named array.

Thus, the following is good:



my @stuff = ( [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] );
print $stuff[0][2];   # prints "3"

push @stuff, \@another_array;
push @stuff, [ qw/this is an array ref/ ];


The following is bad:



my @stuff = ( ( 1, 2, 3 ), ( 4, 5, 6 ), ( 7, 8, 9 ) );
# that just makes a flat nine-element array

push @stuff, @another_array;  # puts another_array in scalar context and pushes its size
push @stuff, ( qw/this is not an array ref/ );  # ditto


You can loop over the nested arrays thusly:



foreach my $rep( @reports ) { 
    foreach my $data( @$rep ) { 
        print "$data
";
    }
}


More here:
http://www.perldoc.com/perl5.8.4/pod/perlreftut.html
http://www.perldoc.com/perl5.8.4/pod/perldsc.html

OK thanks. Hopefully I’ll be able to implement this in the (rather complex) loop when I go back on Linux tomorrow.

OK, after you punched me into submission :), exactly how can these dynamic names be created? Just curious.

Here is an example.

Oops, actually that example has a mistake. ++$varname should be ++$$varname. Here’s a better example.

OK, got it, and will never do it. :slight_smile: