Good point on not needing quoting for the eval.

But no, you don't want the BEGIN in this case. The module won't be required unless a certain option is specified on the command line. So the code must compile even without the module so you can't write the code such that it makes use of prototypes or predeclaration of subroutines (unless you want to duplicate those predeclarations in your code).

So you want something like:

if( need_module_X() ) { if( ! eval { require Module::X; 1 } ) { die "You can't use feature X because Module::X is not installe +d.\n"; } else { Module::X->import( qw( A B C ) ); } }
Note that I added "; 1" because I don't care to memorize or rely on which statements return a true value on success. Note that you can still import routines so that you can call them via A() instead of Module::X::A().

If you do want/need prototypes or predeclaration of subroutines, then you could consider using autouse, though that doesn't give you the custom error message. Otherwise it would look something like:

BEGIN { if( ! eval { require Module::X; 1 } ) { die "You can't use feature X because Module::X is not installe +d.\n" if need_module_X(); sub A { croak "Not available" }; sub B(\%); *B= \&A; sub C(); *C= \&A; } else { Module::X->import( qw( A B C ) ); } }
Untested and unliked. (:

        - tye (but my friends call me "Tye")

In reply to (tye)Re: error message if module doesn't exist? by tye
in thread error message if module doesn't exist? by hellkat

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.