i know about my errors i wrote the post too quickly (in a bit of a time squeeze so read it as a pseudo code)
If you're in a hurry, the best way to get quick answers is to post well-formed questions. Forcing others to fix irrelevant errors in your code can make people less willing to help.
Anyway, I am about 80% sure I understood what you want to do :-) It sounds like the situation you are describing would probably be appropriate for dynamic method calls, but what is still a bit unclear is how you want to handle errors. I think this is relevant for two reasons: First, different functions/methods will throw errors differently - some return undef, some return a negative number, some die, system commands usually return 0 on success, etc. Second, personally I think that in many cases, the best place to handle errors is on the outermost layer of the program, instead of somewhere deep inside several layers - I have seen overuse of try/catch to suppress relevant errors too often. And you might want to consider that designing a new general dispatch mechanism is not something you want to do in a time squeeze, perhaps it's better to reach for existing tools.
If you are looking for a general exception handling mechanism, a place to start might be Try::Tiny.
If by "system command" you mean external programs, then there are several modules to do that with, one of them is my own IPC::Run3::Shell. You can even inherit from IPC::Run3::Shell::Autoload, here's an example where cat is implemented by a method in the package, and any other method calls are autoloaded and turned into system commands, for example the method tac calls the external program tac:
#!/usr/bin/env perl
use warnings;
use strict;
use IPC::Run3::Shell ':FATAL';
use Try::Tiny;
{
package Runner;
BEGIN { our @ISA = ('IPC::Run3::Shell::Autoload') };
sub new { bless {}, shift };
sub cat {
my ($self,$filename) = @_;
open my $fh, '<', $filename or die "cat $filename: $!";
while (<$fh>) {
print "cat: $_";
}
close $fh;
}
}
my $r = Runner->new;
$r->cat('/tmp/test.txt');
$r->tac('/tmp/test.txt');
try {
$r->cat('/tmp/notexist');
}
catch {
warn "Failed: $_";
};
try {
$r->tac('/tmp/notexist');
}
catch {
warn "Failed: $_";
};
__END__
cat: Foo
cat: Bar
cat: Quz
Quz
Bar
Foo
Failed: cat /tmp/notexist: No such file or directory at shell.pl line
+13.
tac: failed to open ‘/tmp/notexist’ for reading: No such file or direc
+tory
Failed: Command "tac" failed: exit status 1 at shell.pl line 31.
|