I'm guessing somewhat regarding what you want to achieve.
Always put strict and warnings at the top of your code.
In this instance, that would have alerted you to the fact that there was something wrong with $f.
I was unsure why you wanted to increment $i inside the loop.
In my version, I changed $i+=2 to $i+2.
Here's a couple of ways of doing what I think you want:
#!/usr/bin/env perl
use strict;
use warnings;
my @f;
# Modification of your code
for my $i (0..2) {
my @e = ($i+2, $i+1);
push @f, [@e];
}
# A more succinct way to achieve it
for my $i (3..5) {
push @f, [$i+2, $i+1];
}
# For demo purposes
use Data::Dump;
dd \@f;
Output:
[[2, 1], [3, 2], [4, 3], [5, 4], [6, 5], [7, 6]]
See also:
"perlintro: Arrays";
"perldsc - Perl Data Structures Cookbook";
"perllol - Manipulating Arrays of Arrays in Perl".
| [reply] [Watch: Dir/Any] [d/l] [select] |
You understand what an array is. If you push an array onto another array, you just wind up with a single bigger single dimensional array. A multi dimensional array is an array of references to array. Push a reference to the @e array onto the @f array. push @f,\@e; I suppose you could write, push @f,[@e], but that would expand @e into an anonymous array and then make a reference to that newly created anon array.
BTW, there can be huge problems if you don't use "my" variables. "my @e" creates a brand new @e array every time this is seen. The push, pushes a reference to the "current @e array". When the loop comes around again, a whole new different @e array is created.
use strict;
use warnings;
use Data::Dump qw(pp);
my @f;
for my $i (0..40)
{
my @e=($i+=2, $i+1); #same as ($i+2, $i+3)
push(@f,\@e);
}
pp \@f;
__END__
Not sure if this is what you want, but
this code results in:
[
[2, 3],
[3, 4],
[4, 5],
[5, 6],
[6, 7],
[7, 8],
[8, 9],
[9, 10],
[10, 11],
[11, 12],
[12, 13],
[13, 14],
[14, 15],
[15, 16],
[16, 17],
[17, 18],
[18, 19],
[19, 20],
[20, 21],
[21, 22],
[22, 23],
[23, 24],
[24, 25],
[25, 26],
[26, 27],
[27, 28],
[28, 29],
[29, 30],
[30, 31],
[31, 32],
[32, 33],
[33, 34],
[34, 35],
[35, 36],
[36, 37],
[37, 38],
[38, 39],
[39, 40],
[40, 41],
[41, 42],
[42, 43],
]
Update: Now that I think about it, $i+=2 is an extremely bad idea. $i is the loop variable. You are asking for big trouble if you attempt to modify the loop variable while you are within the for loop. It does work here, but in general, I would avoid it and go with my ($i+2, $i+3) formulation.
| [reply] [Watch: Dir/Any] [d/l] [select] |
my @f;
for my $i (0 .. 20) {
my @e = (2 * $i, 2 * $i + 1);
push @f, \@e;
}
print map "(@$_)", @f
or you can use the C-style loop to skip over the unwanted numbers:
for (my $i = 0; $i <= 40; $i += 2) {
my @e = ($i, $i + 1);
push @f, \@e;
}
or you can use grep to filter the numbers you want:
for my $i (grep 0 == $_ % 2, 0 .. 40) {
my @e = ($i, $i + 1);
push @f, \@e;
}
etc.
map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
| [reply] [Watch: Dir/Any] [d/l] [select] |