$sheets[1] = \@column;
Perhaps?
As a general proposition, I would worry about this construct -- in particular I would worry whether @column could be changed later, generating side effects in the @sheet array.
However, the following works fine:
Nevertheless, alarm bells might be going off in the back of one's mind: this appears to be assigning a pointer to an "automatic" variable (eek!).my @sheet = () ; while ($line = <SHEET>) { my @columns = split /\s+/, $line ; push @sheet, \@columns ; } ;
It's OK though, you just have to remember that @columns is not really the name of the array, it's the name of a pointer to an array data structure on the heap; and, \@columns isn't returning the address of @columns, it's making a copy of the pointer. When @columns drops out of scope, it's copy of the pointer disappears, but the array data structure stays in the heap until all pointers to it disappear. Obvious, really :-)
The paranoid might worry that @columns might have a life-time of the while loop -- so we'd have to worry about what the assignment does ! Though Perl is, at heart, an interpretted language, so my is an executable item, which might reinitialise @columns each time around the loop, before the assignment ?
It would be easy to make this mistake:
which does leave @sheet with all entries pointing to the same thing: the last line of the input ! (From which we deduce that the assignment to @columns overwrites the array data structure that @columns implicitly points to. Which in some ways is a bit of a surprise ! We also deduce that in the previous case, my @columns within the while loop was reset before the assignment, or was discarded at the end of the loop each time around.)my (@sheet, @columns) ; while (my $line = <SHEET>) { @columns = split /\s+/, $line ; push @sheet, \@columns ; } ;
Anyway, the point here is: when constructing data structures you can use \@foo or \%bar, but in doing so you (a) have to be careful, and (b) have to know what it is you have to be careful about !
is unambiguous and secure -- but I guess requires a copy of the array data to be made. One hopes that:push @sheet, [ @columns ] ;
is bright enough to spot that the list produced by split is already anonymous, so that the [...] needs only to return its address !push @sheet, [ split /\s+/, $line ] ;
In reply to Re^2: One Dimensional Array into Two
by gone2015
in thread One Dimensional Array into Two
by JoeJaz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |