in reply to Re: How Do I Get the Line Number In My Error Message?
in thread How Do I Get the Line Number In My Error Message?

Along the same lines of questioning, I always wanted to know how to write the following DEBUG function:

my $var = 123; DebugPrint("Var is $var.\n"); sub DebugPrint { my $msg = shift; print "Called from $CallingFunction(): $msg"; }

Is it possible to know what function called the DebugPrint() function (in other words, how do you set $CallingFunction)? If so, how?

Replies are listed 'Best First'.
Re^3: How Do I Get the Line Number In My Error Message?
by Corion (Patriarch) on Nov 03, 2005 at 13:31 UTC

    If you want information about your caller, maybe ask Perl about it. The caller function gives you the name of your caller and the line number and file it came from, where applicable.

    sub DebugPrint { my $msg = shift; my ($package,$filename,$line,$subroutine) = caller(1); print "Called from $subroutine(): $msg"; }
Re^3: How Do I Get the Line Number In My Error Message?
by Argel (Prior) on Nov 03, 2005 at 18:39 UTC
    Here is what I do.
    sub whoami { my( $level ) = @_; $level = 1 unless defined $level; print "DEBUG( whoami ): ", (caller(1))[3], "\n" if $DEBUG > $leve +l; return; } sub actually_does_something { whoami(); my( $foo, $bar ) = @_; # Do something useful here }

    -- Argel

Re^3: How Do I Get the Line Number In My Error Message?
by azaria (Beadle) on Nov 03, 2005 at 13:33 UTC
    my intention is to get the caller line number, how can I do that ?

      Read the docs for caller.

      ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller($i);

      You may also want to read "Plain Old Comments (Not!)" and the end of perlsyn -- you can manipulate the file and line numbers that Perl reports.

      -xdg

      Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.