in reply to How can increase number sequence in a variable
Just so you'll know what not to do, here's what you asked for in the OP:
This works with strict (and warnings) fully enabled, but only by invoking no strict 'refs' just before things go sideways.c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "our @A_0; our @A_1; our @A_2; our @A_3; ;; for my $i (0 .. 3) { my $name = qq{A_$i}; no strict 'refs'; $name->[$i] = 1000 + $i; } dd \@A_0; dd \@A_1; dd \@A_2; dd \@A_3; " [1000] [undef, 1001] [undef, undef, 1002] [undef, undef, undef, 1003]
Much better practice is the use of hard references:
Note that the variables being operated on are my (or lexical) variables, but the same referencing mechanism works with package globals (our variables) as well. Note also the \(@ra, @rb, ...) syntax for taking hard references to a collection of (any mixture of) variables. This is just a convenience, and the loop could just as well have been definedc:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my @A_0; my @A_1; my @A_2; my @A_3; ;; for my $arrayref ( \(@A_0, @A_1, @A_2, @A_3) ) { $arrayref->[0] = 1234; } dd \@A_0; dd \@A_1; dd \@A_2; dd \@A_3; " [1234] [1234] [1234] [1234]
The \( ... ) device can be used in conjunction with the declaration of a set of variables and the list of references taken can be captured in an array. The set of references in this array can then be operated on as a group. Note that the \my ( ... ) device can be used only to declare and not to initialize variables. The lexical variables created in the my (@A_0, @foo, @A_2, @A_3) expression below behave just like any lexical; they could also be our variables.
(Update: Thec:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my @arrayrefs = ( \my (@A_0, @foo, @A_2, @A_3) ); ;; for my $i (0 .. $#arrayrefs) { $arrayrefs[$i][$i] = 1000 + $i; } dd \@A_0; dd \@foo; dd \@A_2; dd \@A_3; " [1000] [undef, 1001] [undef, undef, 1002] [undef, undef, undef, 1003]
Update: And here's yet another variation that uses each to simultaneously iterate over the indices and elements of the @arrayrefs array (needs Perl version 5.12+):
c:\@Work\Perl>perl -wMstrict -MData::Dump -le "use 5.012; ;; my @arrayrefs = \my (@A_0, @foo, @A_2, @A_3); ;; while (my ($i, $ar) = each @arrayrefs) { $ar->[$i] = 1000 + $i; } dd \@A_0; dd \@foo; dd \@A_2; dd \@A_3; " [1000] [undef, 1001] [undef, undef, 1002] [undef, undef, undef, 1003]
Give a man a fish: <%-{-{-{-<
|
|---|