$a[$m] = [$m,$m]
uses the array @a
, so you still have to make that into an array reference. You are almost there, but you want
$X->{test_points} = [@a];using
@
not $a
. The difference is that @a
and $a
is a scalar (and generally are two different variables, even though they have the same letter).
So why is $a[$m]
rather than @a[$m]
? Because the entry in the array is a scalar, so you need to use a dollar sign, indicating a scalar value, rather than an at sign (which would indicate an array).
Another reason is that you get a slice of an array using the @
form: @a[1,3,5]
would be a new array made from the first, third, and fifth element of @a
. So technically @a[$m]
should be an array with one element, but because many people get this wrong (and I think it used to be the correct way to do it in very early versions of Perl), Perl handles @a[$m]
as a scalar anyway.
Alternatively, you could use
$P = []; for ($m=0; $m < $N; $m++) { $P->[$m] = [$m,$m]; } $X->{test_points} = $P;to make
$P
a reference to an array, and $P->[$m]
to access the entries in the array.
Another approach would be to assign to the test points directly:
$X->{tet_points} = []; for ($m=0; $m < $N; $m++) { $X->{test_points}[$m] = [$m,$m]; }Here, you could also do
$X->{test_points}->[$m]
, but once you de-reference the first time (using ->
), Perl assumes the remaining de-references when you use braces or brackets.
Finally, a very compact form:
$X->{test_points} = [map { [$_,$_] } (0..$N-1)];This uses the array of integers from 0 to
$N-1
and maps them through code that returns an array reference with two elements, both equal to the integer from the original array. The resulting array of references is put into [...]
so produce a reference to the array.