简体   繁体   中英

Why does concatenating arrays in Perl produce numbers?

I just tried to concatenate arrays in Perl with the + operator and got strange results:

perl -wE 'say([1, 2, 3] + [4, 5, 6])'
73464360

Doing the same with hashes seems to be a syntax error:

perl -wE 'say({} + {})'
syntax error at -e line 1, near "} +"
Execution of -e aborted due to compilation errors.

What is the result of the 1st expression? Is it documented anywhere?

It is from the numification of references, which produces the memory address of the reference.

perl -E 'say \@a; say 0+\@a; printf "%x\n",0+\@a'

Typical output (though it may change every time you run the program)

ARRAY(0x1470518)
21431576
1470518      <--- same number as in first line

Your hash reference example almost works, but it seems that Perl is parsing the first set of {} blocks as a code block rather than as a hash reference. If you use a unary + and force Perl to treat it as a hash reference, it will work. I mean "work".

perl -E 'say(+{} + {})'
40007168

Because + in Perl is an arithmetic operator only. It forces its arguments to be interpreted as numbers, no matter what. That's why Perl has a separate operator for string concatenation ( . ).

What you are doing, effectively, is adding the addresses where the arrays are stored.

Array concatenation is accomplished by simply listing the arrays, one after the other. However, if you are using references to arrays ( [ ... ] ), then you have to dereference them first with @{ ... } :

perl -wE 'say( @{[1,2,3]}, @{[4,5,6]} )'

But normally you would use array variables and not need the extra syntax.

perl -wE 'my @a = (1,2,3); my @b = (4,5,6); say join("-",@a,@b)'
#=> 1-2-3-4-5-6

The same thing goes for hashes; my %c = (%a,%b); will combine the contents of %a and %b (in that order, so that %b 's value for any common keys will overwrite %a 's) into the new hash %c . You could use my $c = { %$a, %$b }; to do the same thing with references. One gotcha, which you are running into in your + attempt, is that {} may be interpreted as an empty block of code instead of an empty hash.

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