Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

__FILE__ and __LINE__ for Perl?

by Plankton (Vicar)
on Oct 02, 2003 at 17:44 UTC ( #295986=perlquestion: print w/replies, xml ) Need Help??
Plankton has asked for the wisdom of the Perl Monks concerning the following question:


I was just wondering if there is a Perl equivalent to C's __FILE__ and __LINE__ ... you know so I could put annoying
print "$__FILE__:$__LINE__ stupid debug message!\n";
statements everywhere.


Plankton: 1% Evil, 99% Hot Gas.

Replies are listed 'Best First'.
Re: __FILE__ and __LINE__ for Perl?
by runrig (Abbot) on Oct 02, 2003 at 17:56 UTC
    You'll find __FILE__ and __LINE__ in perldata under Special Literals (along with __PACKAGE__, and the __END__ and __DATA__ tokens), but since they are literals, they are not prefixed with a sigil and are not interpolated inside quotes:
    print "FILE: ", __FILE__, " Line: ", __LINE__, "\n";
Re: __FILE__ and __LINE__ for Perl?
by dws (Chancellor) on Oct 02, 2003 at 18:00 UTC
    If you're interested in emitting warnings with filenames and line numbers, you might want warn(), which is documented in perlfunc.
    warn "I'm a warning about something";
    will produce
    I'm a warning about something at line 47.

    die() does the same, but stops execution (unless caught in an exception handler).

      Just to be a little more specific, note that
      warn "I'm a warning about something";
      does not contain a trailing newline. If your warning message does contain \n as the last character, warn will not include at line 47.
      See perldoc -f warn

Re: __FILE__ and __LINE__ for Perl? (caller)
by tye (Sage) on Oct 02, 2003 at 18:14 UTC

    If dws's suggestion of warn w/o trailing "\n" isn't good enough, you might want to look into using caller to get more control:

    my $Debugging= ...; sub Trace { return if ! $Debugging; my( $file, $line )= ( caller )[1,2]; warn @_, " at $file:$line\n"; } #... Trace("stupid debug message");

                    - tye
      Why not just use Carp here? croak for die and cluck for warn give you errors from the callers perspective without having to do anythign else.
      use Carp; croak "stupid debug message";
        You mean carp instead of cluck (the latter produces a stack trace as well).

        Makeshifts last the longest.

Re: __FILE__ and __LINE__ for Perl?
by Zaxo (Archbishop) on Oct 02, 2003 at 19:05 UTC

    Also, you can make __FILE__ and __LINE__ lie with the #line directive (perlsyn),

    $ perl -e' > #line 200 "the office" > warn' Warning: something's wrong at the office line 200. $

    After Compline,

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://295986]
Approved by krisahoch
Front-paged by VSarkiss
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2018-05-24 08:37 GMT
Find Nodes?
    Voting Booth?