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


in reply to Line numbers

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'

Replies are listed 'Best First'.
Re^2: Line numbers
by LanX (Saint) on Mar 16, 2012 at 23:18 UTC
    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'
        It is non-obvious why (caller(0))[2] should work but caller(0)[2] should fail.

        Precedence.

        Thanks!

        Personally I don't like referencing for immediate dereferencing.

        But that's a matter of taste...

        Anyway I'd rather prefer a clean named argument solution instead of those silly positional parameters of caller.

        Cheers Rolf

Re^2: Line numbers
by gg48gg (Sexton) on Mar 16, 2012 at 23:12 UTC
    AWESOME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! THANKS!!!!!!!!!!!!!!!