eyepopslikeamosquito has asked for the wisdom of the Perl Monks concerning the following question:
At work, we have a number of long-running scripts. It has been suggested we turn them into modules.
These long-running scripts tend to have a similar structure: they write a running commentary of what they are doing to stdout (via print); they write anything fishy to stderr (via warn); and they die if they encounter a nasty error.
I am eager to learn good ways, general guidelines even, re using print, warn and die inside Perl modules. Error handling, in particular, seems a tricky area of module design. General guidelines and/or examples of well-designed CPAN modules I can study are most welcome.
For the sake of definiteness, suppose we want to call the module in such a way that it never dies and so that all output emitted by the module is written to a log file and to STDOUT simultaneously. I suppose we could try something like this:
sub tee_print { print MYLOGFILE $_[0]; print $_[0] } eval { local $SIG{__WARN__} = \&tee_print; my $h = MyModule->new(PrintHandler => \&tee_print); $h->method($params) or tee_print("oops: " . $h->errstr()); }; if ($@) { tee_print("error: $@") }
Here we have a PrintHandler attribute (use print by default, allow user to override) and an errstr method to return the last error encountered by the module. We could further try this:
my $h = MyModule->new(PrintHandler => \&tee_print, WarnHandler => \&tee_print, ErrMode => 'return'); $h->method($params) or tee_print("oops: " . $h->errstr());
Here we added new WarnHandler and ErrMode attributes, where ErrMode is modelled after Net::Telnet's errmode attribute.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Turning a script into a module
by sauoq (Abbot) on Jul 17, 2003 at 05:16 UTC | |
by MrCromeDome (Deacon) on Jul 17, 2003 at 13:24 UTC | |
Re: Turning a script into a module
by yosefm (Friar) on Jul 17, 2003 at 06:56 UTC | |
Re: Turning a script into a module
by barbie (Deacon) on Jul 17, 2003 at 08:43 UTC | |
by eyepopslikeamosquito (Archbishop) on Jul 17, 2003 at 09:16 UTC |