in reply to Re: BEGIN and compile-time
in thread BEGIN and compile-time

That doesn't do what you expect. The second use Foo::Bar gets executed first, and it gets executed unconditionally.

Why would you want to fallback to the same module anyway? That's the same as not putting a version in the first place! If you wanted to fallback to a different module, the following will do:

BEGIN { my $module = 'Foo::Bar'; require Foo::Bar; eval { Foo::Bar->VERSION(5.01) }; if ($@) { warn(...); $module = 'Foo::Baz'; require Foo::Baz; } import $module qw( ... ); }

VERSION is documented in UNIVERSAL.

Replies are listed 'Best First'.
Re^3: BEGIN and compile-time
by Firefly258 (Beadle) on Nov 09, 2006 at 11:58 UTC
    You're right, and i seem to have overseen the fact that use; statements take execution precedence. Moreover, this particular eval() doesn't work too well as a truth assertion (blaming use) and the subsequent use; gets executed no matter what.

    Why fallback to the same module?? Well, maybe we do need it but ideally we'd like to take control and load the one version of it identified by a supplied version number but if the module at that version isn't available, prepare the script for the standard version and continue, something along the lines of OP's wants.

    So, as has already been examined, "use lib '../'; use Foo::Bar;" seems to have worked simply and elegantly.. but "use lib" places entries at the beginning of @INC and what if non-standard versions of ../strict.pm or ../warnings.pm existed? The user might inadvertently load these modules (OUCH!!) rather than the ones in the original @INC. Placing entries at the beginning of @INC is a bad idea, the risk of polluting the package with bogus code as a result of namespace clashes is real.
    { use lib ".."; use strict; # "../strict.pm" loaded instead of the real one }
    Placing entries at the end of @INC means that modules if found in the original @INC take precendence and are loaded instead of the ones you want loading. The chances are of such a case are slim but entirely possible especially if the user isn't aware of the perl module namespace. Even otherwise, the user might be patching/updating the an already existant module and can ensure the testing release is loaded by using it's $VERSION (wherever the new .pm is located via @INC). Placing entries at the end of @INC is generally safer.

    As an added benefit, using the $Foo::Bar::VERSION to validate loading Foo::Bar also ensures that your code is guaranteed to run under Foo::Bar, alternate versions of the module might break something.

    So if the OP wanted to load a non-standard Foo::Bar (let's assume v5.00) instead of a standard Foo::Bar (v5.01) and provided the version numbers reported by the 2 modules were different (they really ought to be) ...
    #!/usr/bin/perl -W BEGIN { push @INC, ".." } use strict; # "../strict.pm" untouched eval "use Foo::Bar 5.01 qw| raz baz taz |"; # try loading v5.01 if ($@) { # if loading v5.01 failed warn "@_"; # fallback to using standard (v5.00) use Foo::Bar qw| baz |; # raz and taz arent valid tags here } ...

      Placing entries at the end of @INC means that modules if found in the original @INC take precendence and are loaded instead of the ones you want loading. The chances are of such a case are slim but entirely possible especially if the user isn't aware of the perl module namespace.

      I'm not sure why you are advocating adding to the back of @INC or how it relates to the thread, but adding to the front of @INC is definitely the way to go.

      There are two reasons to add to @INC:

      • To have require locate a module that wouldn't get located otherwise. In this case, it doesn't matter if you add to the front or back of @INC since there's only one copy of the module.

      • To have require locate the prefered version of a newer module when require would have locate another version of the module otherwise. In this case, you need to add to the front of @INC.

      So placing it at the front is claearly preferable. There are no reasons to place it at the back.

      what if non-standard versions of ../strict.pm or ../warnings.pm existed?

      You're inventing problems. If .. was added to the end of @INC, your non-standard strict.pm would never get loaded, so why did you write it?


      Now back on topic,

      eval "use Foo::Bar 5.01 qw| raz baz taz |"; # try loading v5.01 if ($@) { # if loading v5.01 failed warn "$@"; # fallback to using standard (v5.00) use Foo::Bar qw| baz |; # raz and taz arent valid tags here }

      You still haven't addressed the problem I mentioned (and fixed) in my previous post. The second use will get executed first, and unconditionally. Since both use load the same module, all you'll get is a Subroutine baz redefined warning. However, it's skirting with danger.

      Furthermore, it doesn't really make sense to import raz and taz from 5.01 if you don't create replacements when loading from <5.01.

      BEGIN { require Foo::Bar; eval { Foo::Bar->VERSION(5.01) }; if ($@) { warn("Warning: Foo::Bar not desired version 5.01. " . "Proceeding anyway\n"); import Foo::Bar qw( baz ); *raz = sub { ... }; *taz = sub { ... }; } else { import Foo::Bar qw( raz baz taz ); } }
        In this case, it doesn't matter if you add to the front or back of @INC since there's only one copy of the module.

        Yes, in this case and at this time but no file system is set in stone, files get moved around and don't you just hate programs that break when files get moved around? what if one have multiple modules of the same namespace?

        You're inventing problems...

        Some bloke said, Programming is 1% code and 99% exception handling. I was just showing how preemptively taking the pains to avoid an exception ensures against the real problems caused by it. Prevention is far better than cure. How many users name their test packages A and B (worse still B::C), easily overseeing the fact that there's a whole array of core/public B modules at the top of the module namespace. In class inheritance, such a misfeature is propogated to child packages. On top of that, @INC is global to all scripts/modules, so your modifications to it is inherited by other code that uses yours; in multiple inheritance scenarios, @INC could be anything but what you expect and you don't want to have caused a code-avalanche for lack of a little preemption, it's always better to be safe than sorry!?!

        <If .. was added to the end of @INC, your non-standard strict.pm would never get loaded, so why did you write it?

         perldoc -f use

        You're completely missing the point of using the VERSION directive with use; to locate and load a precise module irrespective of it's location within @INC. For e.g. The standard strict.pm is now around version 1.03; if my very own ../strict.pm is at version 1.04 and i used this..
        BEGIN { push @INC, ".." } use strict 1.04;
        what do you think a subsequent strict->VERSION() or $strict::VERSION would report?? Note where ".." is placed in @INC. There's no two ways around this, 1.04 it is as ../strict.pm is loaded.
        BEGIN { use lib ".."; # or unshift @INC, ".." } use strict 1.04;
        How about now?? no difference at all.

        You still haven't addressed the problem I mentioned ..

        Well ok, want proof-of-concept and the problem fully addressed?
        #!/usr/bin/perl -lW # catch all bleeping errors BEGIN { push @INC, ".." } my @TAGS = qw| pedantics refs |; my $ideal_version = 1.04; eval " use strict $ideal_version @TAGS; # fails, strict's VERSION==1.03 "; if ($@ =~ /version $ideal_version required.*BEGIN failed/ism) { warn qq|use strict $ideal_version qw(@TAGS); failed, falling back|; shift @TAGS; # Unknown 'strict' tag 'pedantics' eval "use strict qw|@TAGS|"; # which strict is this?? unless ($@) { print qq|second eval, using strict $strict::VERSION qw(@TAGS) fr +om module |, $INC{"strict.pm"}; } } print qq|main now using strict $strict::VERSION qw(@TAGS) from module +|, $INC{"strict.pm"}; if ( grep /pedantics/, @TAGS ) { # newer 'pedantics' related code here # will this run under strict v1.03?? not a chance } else { # workaround for backward compat. # sub pedantics {...}; } if ( grep /refs/, @TAGS ) { # usual 'refs' related code here } else { # quite unlikely to be reached } __END__ __output__ use strict 1.04 qw(pedantics refs); failed, falling back second eval, using strict 1.03 qw(refs) from module /usr/share/perl/5. +8/strict.pm main now using strict 1.03 qw(refs) from module /usr/share/perl/5.8/st +rict.pm
        As you can see, there's No function redefinition errors, no 'magic' invocation of the 'second' use; (outside of the second eval too). The 'second' use is invoked conditionally in a straight-forward, perlish try-catch construct, when and only when the first eval(use ...;) fails. The arrangement of @INC doesn't have an effect on ../strict.pm being overridden either (unless another claiming to be version 1.04 is found before it in @INC, the odds are errm, quite neglible) but again i should emphasize on pushing to @INC not the otherway.

        Since both use; load the same module..

        No, one's explicitly trying to load a module of a specified version, another's falling back to what use; can find, the difference is the first use; will fail if the module at a VERSION is not found, the second one loads the first available one in @INC irrespective of it's VERSION.

        Furthermore, it doesn't really make sense to import raz and taz from 5.01..

        In some ways it does make sense to try and import tags that might not be imported successfully at all, especially in unfamiliar territory, such as - when testing a new module out and/or you are getting a barebones operation running when a newer/standard one isn't available.

        by using use; you can effectively combine something like
        BEGIN { eval { require Foo::Bar; if ($Foo::Bar::VERSION eq 5.01) { import Foo::Bar qw| ... |; } }; revert() if $@; }
        into simpler expressions..
        eval " use Foo::Bar 5.01 qw| ... | "; revert() if $@;
        I favour use; for it's advantage in compile time invocation (preemption again) as opposed to require; which is invoked at run-time, the difference is subtle yet not-so-subtle at the same time, not-so-subtle in terms of longterm keyboard wear-and-tear and premature grey hair, go figure.