in reply to Aborting loading of file in a BEGIN block

Put a block eval around the initial require, and in the file that it gets passed just use the desired module e.g
# in calling file eval { require Your::Module }; require FailSafe::Module if $@; ## Your/Module.pm ## # BEGIN + require + no import use Maybe::Module ();

HTH

_________
broquaint

Replies are listed 'Best First'.
Re: Re: Aborting loading of file in a BEGIN block
by ViceRaid (Chaplain) on Aug 15, 2003 at 15:48 UTC

    Cheers. Unfortunately the require-ing's being done in a context over which I don't have control. I can't alter the code there, I can only change the require-ee.

    ViceRaid

      It sounds like you need to rethink your approach as this isn't simple stuff I'm afraid. There isn't, too my knowledge, a way of avoiding compiling code in a file, short of die()ing in the BEGIN block or some other such hackery. So if you're not too bothered about a bit of symbol table munging, and you want the subs in the current package to disappear on the case of failure then something like this might do
      BEGIN { eval { require Maybe::Module }; $::SPLAT = 1 if $@; } ## *right* at the end of the file if($::SPLAT) { require Symbol and Symbol->import('delete_package'); delete_package(__PACKAGE__); } 1;
      Now in the event of the failure to require the given module the current package will be deleted in it's entirety. If the current package is main or someone else's package, then stick a package Other::Package::__temp at the top and export the subroutines upon success e.g
      package Other::Package::__temp; BEGIN { eval { require Maybe::Module }; $::SPLAT = 1 if $@; } ## *right* at the end of the file if($::SPLAT) { require Symbol and Symbol->import('delete_package'); delete_package(__PACKAGE__); } else { @{caller()."::"}{keys %{__PACKAGE__."::"}} = values %{__PACKAGE__."::"}; } 1;
      That will export the globs in the current package to the caller's package, which should do the trick.
      HTH

      _________
      broquaint

        Thanks - that's great. I can see what I want to do now. Actually it's the require STRING flavour I'm dealing with, so it's maybe a bit easier than I thought. All I want to do is to make sure the subs using Maybe::Module don't blow up when called. I'm doing something like:

        my $no_go; BEGIN { eval { require Maybe::Module }; if ( $@ ) { $no_go = 1 } } sub my_function { print "I'm the normal definition"; } # ... if ( $no_go ) { # safe definition *my_function = sub { carp "Function not available without Maybe::M +odule" }; } 1;

        This works nicely for me; as an aside, I wonder why the BEGIN block can see the my $no_go? I would have expected the BEGIN to run first and so to complain about $no_go failing strict;

        Thanks again
        ViceRaid