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_ = _"
This page shows how variable interpolation works in Perl. Interpolation, meaning "introducing or inserting something", is the name given to replacing a variable with the value of that variable.
Interpolation in Perl refers to the process where the respective values replace the variable names. It is commonly used inside double-quoted strings.
A single leading underscore in front of a variable, a function, or a method name means that these objects are used internally. This is more of a syntax hint to the programmer and is not enforced by the Python interpreter which means that these objects can still be accessed in one way on another from another script.
The use of the variable name _ in any context is never encouraged. The latest versions of Java reserve this name as a keyword and/or give it special semantics. If you use the underscore character (“_”) as an identifier, your source code can no longer be compiled. We will get a compile-time error.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With