First, the syntax @p{$i}
accesses the entry with the key $i
in a hash %p
, and returns it in list context. I don't think you meant that. use strict; use warnings;
to get warned about undeclared variables.
You can declare variables with my
, e.g. my @p;
or my $size = @p
;
Creating variable names on the fly is possible, but a bad practice. The good thing is that we don't need to: Perl has references. A reference to an array allows us to nest arrays, e.g.
my @AoA = (
[1, 2, 3],
["a", "b"],
);
say $AoA[0][1]; # 2
say $AoA[1][0]; # a
We can create an array reference by using brackets, e.g. [ @array ]
, or via the reference operator \
:
my @inner_array = (1 .. 3);
my @other_inner = ("a", "b");
my @AoA = (\@inner_array, \@other_array);
But careful: the array references still point to the same array as the original names, thus
push @other_inner, "c";
also updates the entry in @AoA
:
say $AoA[1][2]; # c
Translated to your problem this means that you want:
my @pn;
for (@p) {
push @pn, [ split /[ ]+/ ];
}
There are many other ways to express this, e.g.
my @pn = map [ split /[ ]+/ ], @p;
or
my @pn;
for my $i ( 0 .. $#p ) {
$pn[$i] = [ split /[ ]+/, $p[$i] ];
}
To learn more about references, read