Why does a variable name follow an underscore that was not correctly evaluated during string interpolation in Perl?

Why is the variable name followed by the underscore not correctly evaluated during string interpolation in Perl?

my $i = 3; print "i = $i\n"; # works, prints "i = 3" print "_i = _$i\n"; # works, prints "_i = _3" print "i_ = $i_\n"; # FAILS, prints "i_ = " print "_i_ = _$i_\n"; # sort of works, prints "_i_ = _" 
+7
source share
4 answers

In addition to other answers, you can use alternative syntax to specify variables:

 print "i_ = ${i}_\n"; 

Note the use of curly braces: { and } to indicate the name of the variable. Whenever in doubt, you can choose this syntax.

+23
source

$i_ is a valid identifier, so it tries to print the value of this variable (which you did not set, so it is undef ).

Include strict and warnings .

+18
source

Mat is right. If you really need this underscore immediately after using the value, use a backslash: "$i\_" .

+7
source

Always use them:

 use strict; use warnings; 
+3
source

All Articles