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_ = _"
Shahriar
  • 280
  • 2
  • 9
  • 10
    [Always use strict and always use warnings!](http://joelslinux.blogspot.com/2011/06/use-strict-and-warnings.html) – Joel Berger Aug 21 '11 at 11:15

4 Answers4

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.

Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
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.

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

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

Itamar
  • 2,111
  • 13
  • 16
  • 2
    `print 'i_ = ' . $i . "_\n";` – Joel Berger Aug 21 '11 at 11:13
  • 6
    I much prefer `${i}` over the backslash, since they do different things in other contexts. – tchrist Aug 21 '11 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 '11 at 15:21
3

Always use these:

use strict;
use warnings;
shawnhcorey
  • 3,545
  • 1
  • 15
  • 17