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

Dose Perl have a predefined variable that equates to the current line number being executed? I already found $PROGRAM_NAME and $EXECUTABLE_NAME which help. 'C' has something like #Line that I'd like to find in Perl. - I would like to be able to do something like ...
open($ProcsA_FILEHANDLE, "<".$File_Spec ) or die("\n\nCould not open $ +File_Spec for read at line number < $What_can_I_put_here_to_Print_Lin +eNumber ? >,in Program $PROGRAM_NAME /n called as executable $EXECUTA +BLE_NAME: : $!\n");

2004-12-23 Janitored by Arunbear - added code tags, as per Monastery guidelines

Replies are listed 'Best First'.
Re: Predefined Variable
by davido (Cardinal) on Dec 23, 2004 at 17:12 UTC

    It does have __LINE__, which evaluates to the number of the line that token resides on. For example:

    print __LINE__, "\n"; print __LINE__, "\n"; my $number = __LINE__; print $number, "\n";

    And the output is:

    1 2 3

    Dave

Re: Predefined Variable
by Eimi Metamorphoumai (Deacon) on Dec 23, 2004 at 17:13 UTC
    From perldoc perldata
    The special literals __FILE__, __LINE__, and __PACKAGE__ represent the current filename, line number, and package name at that point in your program. They may be used only as separate tokens; they will not be interpolated into strings.
    But really, there's no need in this case. If the message you pass to die doesn't end in a newline, Perl will supply the current line number for you.
Re: Predefined Variable
by bmann (Priest) on Dec 23, 2004 at 17:13 UTC
    die does print the line number - unless the last argument to die ends with a new-line. For example:

    perl -e 'die "I died"' outputs "I died at -e line 1." (note the line #)

    If "die" alone doesn't do what you need, __LINE__ should (in most cases).

Re: Predefined Variable (caller)
by tye (Sage) on Dec 24, 2004 at 17:16 UTC

    Even better than __LINE__ is to write a subroutine that adds this information for you (if using die w/o a trailing newlines isn't quite what you want), in which case you'll want to read up on caller.

    - tye