How to Make _ _ LINE _ _ and _ _ FILE_ _ run in perl?

472 views Asked by At

(The Script)

#!/usr/bin/perl
# Program, named literals.perl

written to test special literals

1   print "We are on line number ", _ _LINE_ _, ".\n";
2   print "The name of this file is ",_ _FILE_ _,".\n";
3   _ _END_ _

And this stuff is just a bunch of chitter–chatter that is to be ignored by Perl. The _ _END_ _ literal is like Ctrl–d or \004.[a]

(Output)

1 We are on line number 3.
2 The name of this file is literals.perl.

Explanation The special literal _ _LINE_ _ cannot be enclosed in quotes if it is to be interpreted. It holds the current line number of the Perl script.

The name of this script is literals.perl. The special literal _ _FILE_ _ holds the name of the current Perl script.

The special literal _ _END_ _ represents the logical end of the script. It tells Perl to ignore any characters that follow it.

print "The script is called", _ _FILE_ _, "and we are on line number ",
_ _LINE_ _,"\n";

(Output)

The script is called ./testing.plx and we are on line number 2

I need help getting this example to work. I am having a bit of trouble running it. when i run it on console2 i would get an error stating this

"cant locate object method "_" via package "LINE" (perhaps you forgot to load "LINE"?) at C:\users\john\desktop\console2\test.pl line 5.

Any ideas on how to fix this would be most appreciated. Thanks!

2

There are 2 answers

6
Jonathan Leffler On BEST ANSWER

You need to use names without spaces between the underscores:

#!/usr/bin/env perl
use strict;
use warnings;

print "We are on line number ", __LINE__, ".\n";
print "The name of this file is ", __FILE__, ".\n";
__END__

print "This is not part of the script\n";

When saved in fileline.pl and run, this produces:

We are on line number 5.
The name of this file is fileline.pl.

Note that there are no spaces between the consecutive underscores. And note that the final line containing a print statement is not part of the script because it comes after the __END__. (There's also a __DATA__ directive that can sometimes be useful.)

0
cjm On

There's no space in the literals __FILE__ and __LINE__ (or __END__). Just 2 underscores in a row, the word, and another 2 underscores.