http://www.perlmonks.org?node_id=515670

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

sorry I don't really know how to exactly phase my question. Hopefully the example can show what I can't phase right.
A.pm ----------- package A use B; B->foo(); B.pm ----------- package B sub foo{ die 'your data is screwed'; }
When it dies it yeilds 'your data is screwed at B.pm line x'

what I would like is the die to report 'your data is screwed at A.pm line x'. x being the line number where B->foo was called.

What is the best way to accomplish this?

Replies are listed 'Best First'.
Re: perl deferring die to calling method
by robin (Chaplain) on Dec 09, 2005 at 23:03 UTC
    Instead of using die, use croak from the Carp package. It’s designed for exactly this situation.
    ## This is B.pm ## package B; use Carp 'croak'; sub foo { croak "Your data is screwed"; }
Re: perl deferring die to calling method
by Old_Gray_Bear (Bishop) on Dec 09, 2005 at 23:05 UTC
    Look at Carp.pm:

    carp() -- warns of an error; reports the error as having occured in the calling routine, not the routine that contains the 'carp'.

    ----
    I Go Back to Sleep, Now.

    OGB

Re: perl deferring die to calling method
by ioannis (Abbot) on Dec 10, 2005 at 01:56 UTC
    You could also use caller(). In the example bellow, I have renamed the package name from B.pm to Bb.pm -- so we don't load from the official B namespace.
    package Bb; sub foo { die "your data is screwed at @{[ caller ]}" ; }
Re: perl deferring die to calling method
by bart (Canon) on Dec 10, 2005 at 22:38 UTC
    As an aside, just this warning:
    Do not ever use "B" as a name for a test module.
    The reason is because B actually exists — even more: it comes with perl.
Re: perl deferring die to calling method
by rfojta (Initiate) on Dec 10, 2005 at 11:42 UTC
    I would rather use B::foo(); Try that.

      Hi,

      I would also do so...

      If you were using OO then calling B->foo() would be the best method, but on your example you're not using OO only funcion call, and when calling it with B->foo(), you must know that the first argument in @_ is the package name 'B'.

      So go for B::foo() or take a look at the Exporter module.

      Also is good to read the manuals about perlref, perlboot.

      There was also a module, think it was by Brian D Foy, something to make alias to the package names inside your package scope...

      Regards,

      fmerges at irc.freenode.net
Re: perl deferring die to calling method
by chas (Priest) on Dec 10, 2005 at 20:47 UTC
    Just a comment: as others have implicitly noted, your package declarations should end with a semicolon. (Otherwise, I don't believe your code will compile.)