简体   繁体   中英

difference between the following two codes of [ and ( in perl?

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] ?

Normal parentheses () have no special function besides changing precedence. They are commonly used to confine a list, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM