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

Dear Monks

As my title already (tries to) explains, I would like to know at which line number of my program a print statement occured (in my situation it will be something else, but comparable). It would save me some time if I could directly tell where a problem occured. I tried perlvar but couldn't find this variable (but maybe I missed it).

Any suggestion how to do this ?

Thnx a lot
LuCa
  • Comment on At which line number did the print statement occure?

Replies are listed 'Best First'.
Re: At which line number did the print statement occur?
by davorg (Chancellor) on Oct 13, 2006 at 13:19 UTC
    print 'This is line ', __LINE__;
    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

      Another good one to remember is __FILE__.
        or $0
        Do you know where are all the __LINE__, __FILE__ or __PACKAGE__ documented ?

        Thnx!
Re: At which line number did the print statement occure?
by bart (Canon) on Oct 13, 2006 at 14:01 UTC
    If you don't really want to use warn, which adds the line number by default, then you can replace the print with your own sub, in which you can use caller to check where the sub got called from:
    ($package, $filename, $line) = caller;
    That should suffice to recreate what warn does.

    You can get lots more of info back, if you use a parameter to caller:

    ($package, $filename, $line, @blahblah) = caller(0);

    For example:

    #! perl -w report("Hello, world!"); sub report { my ($package, $filename, $line) = caller; print "print from $filename line $line: @_\n"; }

    Output:

    print from test.pl line 3: Hello, world!
    
Re: At which line number did the print statement occure?
by jbert (Priest) on Oct 13, 2006 at 13:45 UTC
    and it's worth remembering that if you don't put a newline on the end of a warn() (or die()) you'll get the file and line number of the script printed.
Re: At which line number did the print statement occure?
by mrpeabody (Friar) on Oct 14, 2006 at 05:29 UTC
    __LINE__ and friends should be documented in perlvar as well as perldata. perlvar is the logical place to look for this functionality.
      They're data, not variables. (Vary as in change.) Plus, they look a lot like __DATA__ and __END__, which are documented in perldata.
        It's worth noting that the function caller, when used in Windows, returns the line from the first line of actual code.

        #! /usr/bin/perl -w foo() ; sub foo{ print join(" ", caller); }
        This will print '3' as the line number on my Windows machine.
        Bro. Doug :wq