Perl Programming Introduction to mod_perl (part 5): More Perl Basics |
Sometimes it's very hard to understand what a warning is complainingabout. You see the source code, but you cannot understand why somespecific snippet produces that warning. The mystery often results fromthe fact that the code can be called from different places if it'slocated inside a subroutine. Here is an example: warnings.pl ----------- #!/usr/bin/perl -w use strict; correct(); incorrect();
sub correct{
print_value("Perl");
}
sub incorrect{
print_value();
}
sub print_value{
my $var = shift;
print "My value is $var\n";
}
In the code above, % ./warnings.pl we get the warning: Use of uninitialized value at ./warnings.pl line 16. Perl complains about an undefined variable print "My value is $var\n"; But how do we know why it is undefined? The reason here obviously isthat the calling function didn't pass the argument. But how do we knowwho was the caller? In our example there are two possible callers, inthe general case there can be many of them, perhaps located in otherfiles. We can use the
sub third{
second();
}
sub second{
my $var = shift;
first($var);
}
sub first{
my $var = shift;
print "Var = $var\n"
}
The solution is quite simple. What we need is a full calls stack traceto the call that triggered the warning. The warnings2.pl ----------- #!/usr/bin/perl -w
use strict;
use Carp ();
local $SIG{__WARN__} = \&Carp::cluck;
correct(); incorrect();
sub correct{
print_value("Perl");
}
sub incorrect{
print_value();
}
sub print_value{
my $var = shift;
print "My value is $var\n";
}
Now when we execute it, we see: Use of uninitialized value at ./warnings2.pl line 19. main::print_value() called at ./warnings2.pl line 14 main::incorrect() called at ./warnings2.pl line 7 Take a moment to understand the calls stack trace. The deepest callsare printed first. So the second line tells us that the warning wastriggered in print_value(); the third, that script => incorrect() => print_value() We go into Sure, you say, I could find that problem by simple inspection of thecode! Well, you're right. But I promise you that your task would be quitecomplicated and time consuming if your code has some thousands oflines. In addition, under mod_perl, certain uses of the #line 125 it will tell the compiler that the next line is number 125 forreporting needs. Of course the rest of the lines would be adapted aswell. Getting the trace helps a lot.
blog comments powered by Disqus |