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

#!/usr/bin/perl # # SOPW: How does one import things # with Module::Load::Conditional? # # Like: # use IPC::Cmd 'QUOTE'; # use Time::HiRes 'time'; # print join '', QUOTE, time, QUOTE, "\n"; # # So they don't have to be fully qualified for use # like Time::HiRes::time() (<- parens not optional) use 5.9.5; use strict; use warnings; use Module::Load::Conditional 'can_load'; my $modules = { map {$_ => undef} qw/ IPC::Cmd Time::HiRes /}; die "Please install required perl modules: \n". join ' ', 'cpan', keys(%$modules), "\n". join ' ', 'cpanm -v', keys(%$modules), "\n" unless can_load(modules=>$modules, autoload=>1); print join '', IPC::Cmd::QUOTE(), Time::HiRes::time(), IPC::Cmd::QUOTE(),"\n"; #print join '', QUOTE, time, QUOTE, "\n"; # goal

Replies are listed 'Best First'.
Re: Imports with Module::Load::Conditional
by hippo (Archbishop) on Sep 20, 2019 at 14:08 UTC

    You could import them manually after the load:

    #!/usr/bin/perl use 5.9.5; use strict; use warnings; use Module::Load::Conditional 'can_load'; BEGIN { my $modules = { map {$_ => undef} qw/ IPC::Cmd Time::HiRes /}; die "Please install required perl modules: \n". join ' ', 'cpan', keys(%$modules), "\n". join ' ', 'cpanm -v', keys(%$modules), "\n" unless can_load(modules=>$modules, autoload=>1); IPC::Cmd->import ('QUOTE'); Time::HiRes->import ('time'); } print join '', IPC::Cmd::QUOTE(), Time::HiRes::time(), IPC::Cmd::QUOTE(),"\n"; print join '', QUOTE(), time(), QUOTE(), "\n";

    The BEGIN block is only really necessary because time() from Time::HiRes stomps on time so needs to be loaded at compile time. QUOTE works fine without.

      The BEGIN block is only really necessary because time() from Time::HiRes stomps on time so needs to be loaded at compile time. QUOTE works fine without.

      Only if you put the parentheses (which I guess is a good idea though). If you don't import in BEGIN, you'll get Bareword error with QUOTE, time, QUOTE,

      I did try to import manually but neither one worked outside a BEGIN block. The import of time seemed to silently fail, but the import of QUOTE, outside of BEGIN, requires use of QUOTE() instead of just QUOTE, so my test failed. All is well importing at compile time inside BEGIN, thank you for sharing your Perl wisdom!