note
tobyink
<p>This is quite cute - a subclass of [mod://System::Sub] that croaks at compile time if the command cannot be found:</p>
<c>
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' environment variable; stopped");
push @super, $cmd => [%opt];
}
@_ = ($class, @super);
goto \&System::Sub::import;
}
1;
</c>
<p>You can use it like this:</p>
<c>
use System::Sub::Env "mv";
mv("oldname.txt" => "newname.txt");
</c>
<p>At compile time, it will check to see if there's a <c>$ENV{PATH_TO_MV</c> environment variable set, and use <c>mv</c> from there (it should be the full path to the binary). If that's not set, it will fall back to a normal <c>$ENV{PATH}</c> search. And otherwise it will croak, asking them to set the environment variable.</p>
<div class="pmsig"><div class="pmsig-757127">
<small><small><tt>package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name</tt></small></small>
</div></div>
1024253
1024253