Why is a variable name followed by an underscore not evaluated correctly during string interpolation in Perl?
Why is a variable name followed by an underscore not evaluated correctly 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_ = _"
In addition to the other answers, you can use the alternative syntax for specifying variables:
print "i_ = ${i}_\n";
Note the usage of curly brackets: {
and }
to specify the variable name. Whenever in doubt, you may opt for this syntax.
$i_
is a valid identifier, so it's trying to print the value of that variable (which you haven't set, so it is undef
).
Turn on strict
and warnings
.
Mat is right. If you really need that underscore immediately after the value use backslash: "$i\_"
.
Always use these:
use strict;
use warnings;
精彩评论