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

I set some debugging code, which in part is like this:
my $debug = 0; if($debug && $debug == 1) { OPEN(DEBUG,">>/home/path/logs/debug.txt") or die "Could not Open Fil +e for appending: $!"; }
Then I put lines like this:
print DEBUG "Made it to line 3917 where There was an error ['" . $dbh- +>errstr . "'] in the insert\n" if DEBUG && $debug;
However, if I update the script, and insert a bunch of lines, my line numbers are all off.
is there a way for my script to know what line it is on, without having to see it in the browser, so I can have it write it to the file?

Thank you, in advance, Perl Monks :)
Richard

Replies are listed 'Best First'.
Re: Determining a line number the error occurs on
by adrianh (Chancellor) on Aug 13, 2006 at 13:20 UTC

    Take a look at __LINE__ (see perldata for details.)

Re: Determining a line number the error occurs on
by Fletch (Bishop) on Aug 13, 2006 at 13:26 UTC

    __LINE__ aside, you could use warn (with a suitably redirected STDERR or $SIG{__WARN__}) with no trailing newline and Perl will add the location for you.

Re: Determining a line number the error occurs on
by imp (Priest) on Aug 13, 2006 at 16:29 UTC
    My personal preference would be to use Carp.

    use Carp qw(carp cluck); # Print the message with the file and line number included carp("There was an error ['" . $dbh->errstr . "'] in the insert") if D +EBUG && $debug; # Print the message with the stacktrace included cluck("There was an error ['" . $dbh->errstr . "'] in the insert") if +DEBUG && $debug;
    Depending on the layout of your code the line number sometimes isn't enough and you start printing information about who called you. Carp can also upgrade carp to cluck by running perl as follows:
    perl -MCarp=verbose script.pl

    Alternately, you could get the current file and line number like this:

    $context = sprintf '[%s:%d]', __FILE__, __LINE__;
    Or if you wanted to use the stack trace provided by Carp you could get that format like this:
    my $message = sprintf "There was an error ['%s'] in the insert", $dbh- +>errstr; # Print the message with the file and line number included print Carp::shortmess($message); # Print the message with the stacktrace included print Carp::longmess($message);
Re: Determining a line number the error occurs on
by Anonymous Monk on Aug 13, 2006 at 13:48 UTC
    I don't know if this will help, but you can use caller within a subroutine context.