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

Is there an elegant way to return out of a module early? I like the style in subs of something like return unless $arg and wanted something similar in packages/modules. I know I can put all the logic in subs and conditionally call the subs, but TMTOWTDI. This seems to work but is ugly: BEGIN { local $SIG{__DIE__}; die if $check }.

Replies are listed 'Best First'.
Re: Finishing module early
by ikegami (Patriarch) on Apr 23, 2025 at 00:17 UTC

    It's rare to have code at the module level. But if you do, just move it into a sub and call the sub at the top level.

    package Foo; ... sub init { ... return unless $arg; ... } init() 1;
Re: Finishing module early
by Anonymous Monk on Apr 22, 2025 at 14:12 UTC
    That you're asking this question means you're not using modules correctly. Put all of your code in one or more subs and return from them.
Re: Finishing module early
by kcott (Archbishop) on Apr 26, 2025 at 04:28 UTC

    While TMTOWTDI is certainly a feature of Perl, it's unclear exactly what you're attempting to achieve.

    Based on what you have written, I tend to agree with AM's comment, perhaps with a small qualification: "... you're probably not using modules correctly ...".

    The following points are somewhat simplistic. I'd be happy to expand upon them when you've clarified your intent.

    • The most common usage is to load a module at compile time (see use) then access its subroutines as required.
    • You can conditionally load a module at compile time using the if pragma.
    • You can (conditionally) load a module at runtime using the require function.

    If you provide a short piece of code to demonstrate your use case, we'd have a better idea of what you're trying to do. This may lead to a better answer.

    I'd also strongly recommend that you Create A New User — this is a very simple process and, unlike other forums, does not require you to provide a lot of personal information. This allows us to differentiate your posts from thousands of other anonymous posts. It also has many benefits for you (non-exhaustive list): search for your own posts; edit your posts; customise your PerlMonks experience; access many features only available to logged in users.

    — Ken