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.


In reply to Turning a script into a module by eyepopslikeamosquito

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.