Reputation: 89
When I want to assign input file to array, I am getting this error.
while (<>) {
my @tmp = split;
push my @arr,[@tmp];
print "@arr\n";
}
output: ARRAY(0x7f0b00)
ARRAY(0x7fb2f0)
If I change [
to (
then I am getting the required output.
while (<>) {
my @tmp = split;
push my @arr,(@tmp);
print "@arr\n";
output: hello, testing the perl
check the arrays.
What is the deference between (@tmp)
and [@tmp]
?
Upvotes: 1
Views: 85
Reputation: 67910
Normal parentheses ()
have no special function besides changing precedence. They are commonly used to confine a list, e.g. my @arr = (1,2,3)
Square brackets return an array reference. In your case, you would be constructing a two-dimensional array. (You would, if your code was not broken).
Your code should perhaps be written like this. Note that you need to declare the array outside the loop block, otherwise it will not keep values from previous iterations. Note also that you do not need to use a @tmp
array, you can simply put the split
inside the push
.
my @arr; # declare @arr outside the loop block
while (<>) {
push @arr, [ split ]; # stores array reference in @arr
}
for my $aref (@arr) {
print "@$aref"; # print your values
}
This array would have the structure:
$arr[0] = [ "hello,", "testing", "the", "perl" ];
$arr[1] = [ "check", "the", "arrays." ];
This is a good idea if you for example want to keep lines of input from being mixed up. Otherwise all values end up in the same level of the array.
Upvotes: 7