Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Line numbers

by tobyink (Canon)
on Mar 16, 2012 at 23:02 UTC ( #960087=note: print w/replies, xml ) Need Help??

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 (Sage) 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.



        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!!!!!!!!!!!!!!!

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://960087]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2022-01-25 19:41 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (67 votes). Check out past polls.