Re: How Do I Get the Line Number In My Error Message?
by japhy (Canon) on Nov 03, 2005 at 13:08 UTC
|
The special tokens __FILE__ and __LINE__ report the filename and line number of the current source file you're in. They do not interpolate into quoted strings, though.
| [reply] |
|
|
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? | [reply] [d/l] |
|
|
sub DebugPrint {
my $msg = shift;
my ($package,$filename,$line,$subroutine) = caller(1);
print "Called from $subroutine(): $msg";
}
| [reply] [d/l] |
|
|
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
}
| [reply] [d/l] |
|
|
my intention is to get the caller line number, how can I do that ?
| [reply] |
|
|
|
|
Does this token _FILE_ is the name of the program (=$0) ?
| [reply] |
|
|
If you only have one file, yes, $0 will refer to the same file as __FILE__.
If your program has more than one file (for example, if your code is a perl module), __FILE__ is more useful; $0 will tell you the name of the file that perl started running, but __FILE__ will tell you the file where you code is currently running. If you use the commands "require", "do", "use", __FILE__ will keep track of where the code came from: it's very handy.
Also, notice that it's __FILE__ (with two underscores before and after the word), not _FILE_ (with one underscore).
You might want to look at the module called "Carp": if you say "use Carp"; and then use the function "carp" where you would use the function "warn", you'll get messages that include the current line number, all the functions called to reach the current function, with file names and line numbers.
Good Luck! :-)
--
Ytrew
| [reply] |
Re: How Do I Get the Line Number In My Error Message?
by reasonablekeith (Deacon) on Nov 03, 2005 at 16:36 UTC
|
I'm confused by the replies you've received. Aren't you just after the sort of debugging info that is provided by Carp?
#!/perl -w
use Carp;
a_test_sub();
sub a_test_sub {
confess("uh oh");
}
__OUTPUT__
uh oh at test.pl line 7
main::a_test_sub() called at test.pl line 4
---
my name's not Keith, and I'm not reasonable.
| [reply] [d/l] |
Re: How Do I Get the Line Number In My Error Message?
by spatterson (Pilgrim) on Nov 04, 2005 at 13:32 UTC
|
| [reply] |