Hey again monks,

I run up against this design decision a lot and figured I'd better ask for some wisdom before continuing with what feels like a bit of an odd workaround.

Module:

# perl -w package test_caller; if (caller) { print 'imported'; return 1; } else { print 'direct execution'; } print ' do not need to end in truth'; 0; # 'direct execution do not need to end in truth'

Script:

#! perl -w use test_caller; # 'imported'

This works fine. For a little I was mixed up between exit codes and module import return value. I need to explicitly return 1; in order to make sure that the module stops execution there for importers and returns truth. For some reason I was laboring under the misconception that use checks the exit code when in fact it only cares about the return value.

I am aware that implementing this sort of thing isn't entirely sane. Best practice dictates that I keep module and script functionality separate. But I end up with a lot of scripts that turn into modules because they have lots of useful code for other scripts. But I'd like to keep the ability to run these module-ified scripts standalone.

Anyway, relying on caller feels a little bit hacky. So I'm looking for opinions/advice/admonishment regarding a better way to distinguish between a module being executed directly versus being imported?


In reply to Flexibility in Module for Import or Execute by temporal

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.