8

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_ = _"
1

4 Answers 4

26

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.

18

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

1
  • I noticed your buddhabrot, Mat. Perhaps this would interest you: github.com/buddhabrot/buddhabrot (I couldn't reach you any other way so I had to find an innocent comment somewhere).
    – buddhabrot
    Dec 7, 2011 at 16:48
7

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

3
  • 2
    print 'i_ = ' . $i . "_\n"; Aug 21, 2011 at 11:13
  • 6
    I much prefer ${i} over the backslash, since they do different things in other contexts.
    – tchrist
    Aug 21, 2011 at 14:22
  • 3
    A backslash suppressed interpolation. Curlies around a variable name interpolate the value of that variable. print "${i}_\n" is easier on my eyes and brain, because those two things would do the same thing if unquoted.
    – tchrist
    Aug 22, 2011 at 15:21
3

Always use these:

use strict;
use warnings;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.