String concatenation in Perl, providing function output, etc.

The following code does not output anything:

print (1 == 2)."a"; 

How does it do:

 print qw< One Two Three > . "a"; 

But this displays a snowman followed by the letter a, as expected:

 print chr(0x2603)."a"; 

Is there a general method for concatenating common β€œthings” due to the lack of a better word (for example, outputting a function and the results of logical comparisons) with string fragments that always work? Because the operator . doesn't seem reliable.

+6
source share
1 answer

This is expected behavior due to the way lists and contexts work in Perl.

What's happening

Line

 print (1 == 2)."a"; 

It is analyzed as follows:

 ( print( 1 == 2 ) . "a" ) 

Since 1==2 returns an empty string, nothing is printed. The return value from print itself is then combined with a and discarded.

If you enabled use warnings (which you should always do with use strict ), you would see:

print (...) is interpreted as a function on -e line 1.
Useless use of concatenation (.) Or string in void context on -e line 1.

Line

 print qw< One Two Three > . "a"; 

Indeed, type the string Threea . This is because qw< One Two Three > equivalent to the expression ( 'One', 'Two', 'Three' ) . Concatenation operator . puts this expression in a scalar context, and the behavior of the comma operator in a scalar context is to return its right operand. So the expression boils down to Threea . Again, if you had warnings , you would see:

Useless use of a constant ("One") in a void context on -e line 1.
Useless use of a constant ("Two") in the void context on -e line 1.

Moral of history

 use strict; use warnings; 
+12
source

All Articles