Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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_ = _"
like image 505
Shahriar Avatar asked Aug 21 '11 11:08

Shahriar


People also ask

Does Perl allow variable interpolation?

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.

What is interpolation in string in Perl?

Interpolation in Perl refers to the process where the respective values replace the variable names. It is commonly used inside double-quoted strings.

What does putting an underscore before a variable mean?

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.

Can we use underscore in variable name?

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.


2 Answers

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.

like image 112
Alan Haggai Alavi Avatar answered Sep 20 '22 06:09

Alan Haggai Alavi


$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.

like image 31
Mat Avatar answered Sep 21 '22 06:09

Mat