http://qs321.pair.com?node_id=960085

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

I know that there is die and warn, but I have a need to create my own subroutines for handling warnings, errors, fatal_errors, etc.

I am trying to print the line number for which the error occurred. Code is below, however, it prints the line number of the subroutine instead of the line number I meant......

I would like to have the code to print the correct line number within the subroutine, rather than passing __LINE__ to the subroutine. Is this possible?

open (FILE,"<","/etc/doesnotexist") || fatal_error("can't open /etc/do +esnotexist, sorry"); sub fatal_error { print STDERR "ERROR: ", @_," ",__LINE__; usage(); exit 1; }

Replies are listed 'Best First'.
Re: Line numbers
by tobyink (Canon) on Mar 16, 2012 at 23:02 UTC

    Don't use __LINE__.
    Instead use [caller(0)]->[2].

    See the documentation for the caller function in perlfunc.

    Full example:

    sub fatal_error { print STDERR "ERROR: ", @_," ",[caller(0)]->[2]; usage(); exit 1; }
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
      is there any advantage of [caller(0)]->[2] over (caller(0))[2]?

      Cheers Rolf

        Indeed there is an advantage of the first - I can remember the syntax.

        It is non-obvious why (caller(0))[2] should work but caller(0)[2] should fail.

        Also, the arrayref plays nicer associativity wise. Check this out:

        $ perl -E'sub x { say [caller(0)]->[0] } x()' main $ perl -E'sub x { say (caller(0))[0] } x()' syntax error at -e line 1, near ")[" Execution of -e aborted due to compilation errors.

        The version with the arrayref just acts more predictably in my mind. I don't have to waste time thinking about it.

        perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
      AWESOME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! THANKS!!!!!!!!!!!!!!!
Re: Line numbers
by Marshall (Canon) on Mar 16, 2012 at 23:54 UTC
    As an additional reference: Perl Cookbook: Determining Current Function Name, might serve you well. See the whoami() and whowasi() functions.

    update: link disabled - may not be an official online copy - although some of these O'Riley books are available legitimately online