suaveant has asked for the wisdom of the Perl Monks concerning the following question:

I have a module that I want to run a check in a BEGIN block and if that check fails the module stops processing but allows the program to continue (so no other use or BEGINs happen) Is that possible without turning my use statments into
BEGIN { unless($skip) { require Config; Config->import(); ... } }
?

                - Ant
                - Some of my best work - (1 2 3)

Replies are listed 'Best First'.
Re: Aborting a module
by almut (Canon) on Oct 23, 2007 at 19:03 UTC

    You might want to use the if module to make the use statements conditional:

    use if !$skip, 'Config';
Re: Aborting a module (return 1)
by tye (Sage) on Oct 23, 2007 at 19:09 UTC

    You can return 1; from a module and the rest won't be processed. I suspect that would also work from a BEGIN block but I'll let you test that.

    - tye        

      I thought that BEGIN { } was just magic subroutine, so a return just returns from the BEGIN block. My tests seem to confirm this:
      sub BEGIN { print "hello\n"; return 1; } print "bye\n"

      prints (wait for it...)

      hello bye

        Yes, precisely. I should have realized that. Thanks.

        - tye        

      Like this? It seems to continue past the BEGIN block.
      $ perl -wl use strict; BEGIN { return 1; } print "foo"; __END__ foo
      --
      Andreas

        Rereading the root node, the BEGIN was an example of a complicated way of using the module rather than code within the module. So the following should work fine:

        package My::Module; if( ... ) { # This module is useless in this case: return 1; } ... 1;

        Another possiblity is:

        package My::Module; if( ... ) { require My::Module::Internal; } 1;

        - tye        

        Confirmed, it doesn't work from within BEGIN.

        >type M.pm package M; BEGIN { return 1; } print "Point A\n"; return 1; print "Point B\n"; 1; >perl -e "use M;" Point A
      Yeah... it's annoying... you can return from the BEGIN block but it doesn't stop anything except the processing of the rest of that BEGIN. Ah well.

                      - Ant
                      - Some of my best work - (1 2 3)

Re: Aborting a module
by jettero (Monsignor) on Oct 23, 2007 at 18:36 UTC

     BEGIN{ eval "use $packagename"; $package_didnt_work =1 if $@ } maybe?  if( $something ) { eval "use Something"; }?

    -Paul