http://www.perlmonks.org?node_id=295986

Plankton has asked for the wisdom of the Perl Monks concerning the following question:

Friends,

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.

Thanks

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 demo.pl 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 demo.pl line 47. See perldoc -f warn

      --
      bm
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,
    Zaxo