A standard way to catch errors is to use die (or Carp), in combination with eval. But since I prefer Try::Tiny, I'm going to use that.
For example:
#!/usr/bin/perl
use strict;
use warnings;
use Try::Tiny;
$main::errorA = 1;
$main::errorB = 1;
sub methodA {
if ($main::errorA) {
die "Something went wrong in methodA";
}
}
sub methodB {
my ($handle) = @_;
&$handle();
if ($main::errorB) {
die "Something went wrong in methodB";
}
} ## end sub methodB
my $rowHandle = \&methodA;
try {
methodB($rowHandle);
}
catch {
print ("ERROR: " . $_);
}
This results in:
ERROR: Something went wrong in methodA at ./monks24.pl line 12. (monks24.pl being the name of the executable).
This is because errorA is checked before errorB.
If you'd set errorA to 0 (meaning all is well in methodA), you'd get this:
ERROR: Something went wrong in methodB at ./monks24.pl line 20. | [reply] [d/l] [select] |
my $rowHandle = \&methodA;
if(!methodB($rowHandle)){ # If you want to PASS the method
...
sub methodB(){
my $handle = $_[0];
$handle->(); # CALL the method
I hope life isn't a big joke, because I don't get it.
-SNL
| [reply] [d/l] |
This might be a good place to use a closure. (Google it; see perldoc perlref.) Basically, the caller passes a reference to a subroutine that is to be called, and when that call occurs, it will happen in the context that existed when it was made. The routine that constructs the closure is thus able to know and to dictate not only what happens but also in what context it happens. (It can refer to private variables, etc.) The routine that executes it, now, does not have to know one closure from another. All he has to do is to push that button; you determine what happens.
Conceptually, instead of passing a set of instructions that the other guy has to do (and, thus, making your correct-behavior dependent upon some distant piece of software “doing the right thing”), you instead hand him a tidy, self-contained box with a “Push Me” button on top. All he has to do is to push that button. You control everything that happens next.
| |