Hi -
I've been knocking my head against this for hours now, and I can't seem to get it right. (v5.8.8 from Activestate on Windows XP).
I have a list of modules I want to use, but only if they're available (i.e. installed on the system the script is running on and included in @INC). If they're not available, I want the code that calls them to be skipped. Installing them isn't an option, period. Oh, how I wish it were, but it's not.
Here is an example (line numbers added for clarity):
000: my $fname = $ARGV[0];
001: open(FILE, $fname) or die "Can't open file!";
002:
003: my $can_foo=1;
004: eval "use FOO::bar";
005: if($@) { $can_foo=0; } #Don't try to use if unavailable
006:
007: #later on in the program, maybe multiple times.
008:
009: if ($can_foo) {
010: my $foobarzlot=sprintf("%d,",bar(FILE)->zlot);
011: print "FOOBARZLOT=".$foobarzlot."\n";
012: }
My goals are:
1. Avoid a compile-time error when FOO::bar is unavailable. The "eval" in line 004 prevents this quite nicely.
2. Avoid a run-time error on line 010 when FOO::bar is available.
I'm not doing so well with the second objective. Everything I've tried seems to result in a run time error like "Can't call method "zlot" without a package or object reference at foobarzlot.pl line 10." Yet, FOO:bar is right there on the development system and should return a valid "zlot" with no problem at all. If I put the use (or require) statement outside the eval, everything works perfectly. Unfortunately, having no influence on what's installed on the target system(s), it's virtually guaranteed that some systems will barf at compile time.
P.S. If you replace FOO::bar with File::stat and zlot with size, you'll get a better idea. I just didn't want people to get hung up on the choice of module. I have about ten different modules I need to use or not-use based on availability.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.