Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Executing a program from within a Perl Module in a non-standard path

by tobyink (Abbot)
on Mar 19, 2013 at 13:41 UTC ( #1024296=note: print w/ replies, xml ) Need Help??


in reply to Executing a program from within a Perl Module in a non-standard path

This is quite cute - a subclass of System::Sub that croaks at compile time if the command cannot be found:

use v5.10; use strict; use warnings; package System::Sub::Env; use Carp qw(croak); use File::Which qw(which); use base qw(System::Sub); sub import { my $class = shift; my @super; while (@_) { my $cmd = shift; my %opt = @{ ref($_[0]) ? shift : [] }; my $env = uc("PATH_TO_$cmd"); $opt{'$0'} //= ($ENV{$env} // which($cmd)); -x $opt{'$0'} or croak("Could not find '$cmd'; please set '$env' environ +ment variable; stopped"); push @super, $cmd => [%opt]; } @_ = ($class, @super); goto \&System::Sub::import; } 1;

You can use it like this:

use System::Sub::Env "mv"; mv("oldname.txt" => "newname.txt");

At compile time, it will check to see if there's a $ENV{PATH_TO_MV environment variable set, and use mv from there (it should be the full path to the binary). If that's not set, it will fall back to a normal $ENV{PATH} search. And otherwise it will croak, asking them to set the environment variable.

package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name


Comment on Re: Executing a program from within a Perl Module in a non-standard path
Select or Download Code
Re^2: Executing a program from within a Perl Module in a non-standard path
by GoldElite (Acolyte) on Mar 20, 2013 at 11:53 UTC

    Ahh, this is pretty cool. I like the idea that System::Sub represents, but alas, it requires that I know where the executable (or script!) will be at compile time (at least, relative to the cwd).

    As an aside, I can't understand how import doesn't get itself in an infinite loop! Where's the exit?!

     

    But thanks; I'll definitely keep this class in mind for later projects

      "As an aside, I can't understand how import doesn't get itself in an infinite loop!"

      System::Sub::Env::import is going to System::Sub::import. Different package; different sub.

      The reason for the goto is to hide System::Sub::Env::import from the call stack - System::Sub's import method looks at caller.

      package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1024296]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2014-09-15 03:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (145 votes), past polls