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

How is it possible to get the line number in the main program from within a modulesubroutine? In other words, how does carp know where i called the croak function?

Replies are listed 'Best First'.
Re: line number
by Molt (Chaplain) on Sep 12, 2002 at 13:58 UTC

    It's all done by the caller function, do a perldoc -f caller to see how. The following is a quick demo..

    #!/usr/bin/perl use strict; use warnings; test(); sub test { # Get info from the caller my ($package, $file, $line) = caller; print "Called from $line of $file in $package\n"; }

Re: line number
by jkahn (Friar) on Sep 12, 2002 at 14:00 UTC
    carp and croak traverse the values returned by the caller() builtin function (see perldoc -f caller).

    The code inside the Carp module is pretty hairy stuff, but it makes for interesting reading. I found the most interesting parts were the sections of code added so that the warning was issued in the code outside the package -- or any child or parent package -- so that OO Perl still works. Neat stuff.

    Added:The Carp code travels up the call stack (via caller()) until it finds the first routine that calls itself that isn't in the current package (or one of its relatives, so that method inheritance works).

Re: line number
by Jaap (Curate) on Sep 12, 2002 at 14:12 UTC
    Wow it works! Thank you so much.
Re: line number
by dmitri (Priest) on Sep 12, 2002 at 21:36 UTC
    Here's a quicky I sometimes use:

    $linenum = &{sub{(caller)[2]}};
      How is that different from:
      $linenum = __LINE__;

      -Blake

        dmitri said:
        $linenum = &{sub{(caller)[2]}};
        blakem said:
        $linenum = __LINE__;

        dmitri's solution returns the line number of the call tothe line in the current subroutine.

        blakem's solution returns the line number of the __LINE__ within the current subroutine.

        Amended 4:10p PDT I'm not sure why dmitri is building a subroutine reference only to call it. dmitri, do you care to clarify?

        At 4:15, after reading blakem's follow-up, I realize blakem is right. dmitri's would be different, if he'd said:

        $linenum = (caller)[2];
        but he didn't. So they are equivalent, and I must say that __LINE__ is much simpler.