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

I apparently do not understand how to do this so if someone could teach me some theory so I will know how to do it on the next module I would appreciate it. I am trying to change two static use's into dynamic require/import so I can adjust platform to platform with what is available. Her eare toe use statements: use Capture::Tiny ':all'; use IPC::Run qw(run new_chunker start pump finish timeout); use Capture::Tiny qw/capture/;

if (eval { require Capture::Tiny } ) { print "Using Capture::Tiny\n"; use subs qw/capture/; Capture::Tiny -> import ( qw/capture/ ); ( $SpoolFile -> [0], $CMDERR[0], $ReturnCode ) = capture { system qq[ echo Hello, World | cat ]; } } elsif (eval { require IPC::Run } ) { print "Using IPC::Run\n"; use subs qw ( run new_chunker start pump finish timeout ); IPC::Run -> import ( qw (run new_chunker start pump finish tim +eout ) ); ... }

On the call to capture I get: Can't call method "capture" without a package or object reference at ./ line 5. On the second I get: Prototype mismatch: sub main::new_chunker: none vs (;$) at /usr/share/perl5/ line 67. I would appreciate it someone could clear the haze.

Replies are listed 'Best First'.
Re: Help Changing use into require/import
by Discipulus (Abbot) on Mar 07, 2018 at 21:21 UTC
    Hello computergeek and welcome to the monastery and to the wonderful world of Perl!

    You can also be interested into Module::Load::Conditional

    PS also note that the folowing works:

    perl -e " my $rc; BEGIN{ + $rc = eval{require Capture::Tiny; Capture::Tiny->import ('capture'); 1; } } if ($rc){ ($SpoolFile->[0],$CMDERR[0],$ReturnCode)=capture{sy +stem qq[ echo Hello, World | cat ]}; print join ', ', $ReturnCode, $SpoolFile->[0]; } " 0, Hello, World

    Infact use is equivalent to BEGIN { require Module; Module->import( LIST ); } as per use docs.

    PPS see also some other links about compile time / run time


    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

      I wrote Plugin::Simple, primarily because I had a bit of time and wanted to write my own basic plugin architecture for a learning exercise. Here's a runtime snip of actually loading a plugin. It can be in the form of a file name with a path, a filename without a path, or a standard Module::IAm syntax. The load() function is brought in from Module::Load.

      The conditional load doesn't affect the program, it simply determines whether the plugin name will be returned to the caller:

      sub _load { my ($self, $plugin) = @_; if ($plugin =~ /(.*)\W(\w+)\.pm/){ unshift @INC, $1; $plugin = $2; } elsif ($plugin =~ /^(\w+)\.pm$/){ unshift @INC, '.'; $plugin = $1; } my $loaded = eval { load $plugin; 1; }; if ($loaded) { return $plugin; } }
Re: Help Changing use into require/import
by haukex (Bishop) on Mar 08, 2018 at 10:48 UTC
Re: Help Changing use into require/import
by VinsWorldcom (Prior) on Mar 07, 2018 at 20:59 UTC

    UPDATE: This *could* be bad advise, see the reply node at Re^2: Help Changing use into require/import by stevieb.

    The way I do this, certainly there are other ways:

    my $HAVE_Capture_Tiny = 0; eval "use Capture::Tiny qw(capture)"; if ( !$@ ) { $HAVE_Capture_Tiny = 1; } ... if ( $HAVE_Capture_Tiny ) { my $c = Capture::Tiny->new( ... ); } else { ## fallback if not have Capture::Tiny }

    UPDATE 2: Based on the nodes below, my new way of doing this:

    use strict; use warnings; # Instead of: # # use Module::Name 1.00 qw(:subs); # # do this: my $HAVE_Module_Name; BEGIN { $HAVE_Module_Name = eval { require Module::Name; Module::Name->VERSION( 1.00 ); Module::Name->import( qw ( :subs ) ); 1; }; } if ($HAVE_Module_Name) { print "Module::Name = $Module::Name::VERSION\n"; } else { print "Module::Name = [NOT INSTALLED]\n"; }

      Not putting down the way you do it, but just checking $@, particularly without checking what's in it could be problematic in some cases (ie. the variable could potentially be set during this check, unrelated to your eval(), which would technically trigger a false-positive failure). Any eval error happening in the require could also fail with an error, but your eval will reset this var to undef as soon as it starts. Here's a very similar way that does kind of the same thing, but checks the state of the eval, not whether there's an error. It also uses block eval as opposed to string eval:

      BEGIN { # look for JSON::XS, and if not available, fall # back to JSON::PP to avoid requiring non-core modules my $json_ok = eval { require JSON::XS; JSON::XS->import; 1; }; if (! $json_ok){ require JSON::PP; JSON::PP->import; } }

      What happens there is that if any of the lines prior to the 1; in the eval fail, the eval block will return false (undef to be specific). If all expressions within the eval succeed, the $json_ok variable will be true, and we can proceed confidently.

      See a number of issues with eval in the Try::Tiny documentation (which could be, after all, a different approach to the OP's problem. To be honest, I've never used said distribution that I recall).

        Good point.

        My goal in this was to be able to use more complicated "use" statements like:

        use My::Module 0.04 qw( :sub1 :sub2 );

        I just can't seem to get those to work with the require / import way so needed a way to "use", which didn't blow up if the module wasn't found. I'm sure I didn't "invent" this; rather, Google-d, found something and used it without understanding the implications you pointed out. And I've just been "using" it ever since.

        I wonder if "undef $@" before the 'eval' would help ensure any error ending up in $@ is coming from the eval?

      I tried your code and get this error: Can't locate object method "new" via package "Capture::Tiny" at ./ line 40. I am not sure if this means I am dead in the water or if there is another way. When I was doing research on import it appears the module writer is the one who implements and it is not a generic perl feature.

        Can't locate object method "new" via package "Capture::Tiny" at ./ line 40

        Capture::Tiny doesn't have a new() method, and Capture::Tiny->new() will therefore fail irrespective of how you loaded the module.


        That's just my quick example. There is no new() constructor in Capture::Tiny, I was just throwing down a quick template and overlooked that. That'd be where you use the capture() sub you imported.

Re: Help Changing use into require/import
by Anonymous Monk on Mar 08, 2018 at 17:14 UTC

    Generally in a case like this I use either BEGIN blocks or fully-qualified names, whichever seems appropriate. In this case the latter seems a better fit:

    #!/usr/bin/env perl use strict; use warnings; my ( $stdout, $stderr, $errcode ); if (eval { require Capture::Tiny } ) { print "Using Capture::Tiny\n"; ( $stdout, $stderr, $errcode ) = Capture::Tiny::capture( sub { system "echo Hello, World | cat"; } ) } elsif (eval { require IPC::Run } ) { print "Using IPC::Run\n"; no warnings qw{ qw }; # Otherwise Perl complains about the comm +a IPC::Run::run( [ qw{ echo Hello, World } ], \'', '|', [ 'cat' ], \$stdout, \$stderr ); } print "STDOUT: $stdout";
Re: Help Changing use into require/import
by Anonymous Monk on Mar 11, 2018 at 09:36 UTC
    capture { system qq[ echo Hello, World | cat ]; }

    Can't call method "capture" without a package or object reference

    Hypothesis (untested): if you do Capture::Tiny::->import("capture"); at BEGIN time, like use does, Perl knows the prototype of the capture function (which contains & and makes it accept blocks which are really anonymous subroutines without sub keyword). If you do the import at runtime, the subroutine is still imported (you can call it without fully qualifying Capture::Tiny::capture), but it's too late for Perl parser to change its understanding of your code: instead of capture(sub{...}), it sees {...}->capture and fails.