In Unix shell script we check the exit status of the previous command using the value of
$?
where zero equals success. How can I do it in Perl?When I run
perl -V
I see some paths listed in@INC
. How do I add new paths to@INC
?How can I set the order of arguments in the
GetOptions
function? I want-email
to be the first argument and if it's given as second argument it should fail.GetOptions( 'nemail' => sub {$ENV{EMAIL} = "Y"}, 'arg' => \$help );
What is the difference between the extensions
.pl
and.pm
? When do I need to use the.pm
extension?When I write
use File::Copy
, where is the code located? Which enviroment variables doesuse
access?
views:
85answers:
1External commands are launched with the
system
function, it also sets the child error variable$?
/$CHILD_ERROR
. Instead of doing those checks yourself, useautodie
:require IPC::System::Simple; use autodie qw(:all); system([0], 'foobar-command', '--option', '--yet-another-option'); # 0 is allowed as an exit status, others will throw an exception
Internal programming constructs, e.g. subroutines from modules, use error checking that goes beyond from what you know from shell programming. There is more than one way to do it. Most of the type, success and failure is signalled by the return value of a function, often
undef
means failure, e.g. by reading the documentation forFile::Copy
we learn that the return value is 0 for failure and also the usual other error variable is set.use English qw($OS_ERROR) use File::Copy qw(mv); my $source = '/does_not_exist'; my $destination = '/tmp'; unless (mv($source, $destination)) { warn "Move from $source to $destination failed: $OS_ERROR"; }
Another possibility is exceptions. You have to learn this in detail: chapter 13 of PBP and chapter 11 of EPP.
use Try::Tiny; my $string; try { $string = Encode::decode('UTF-8', $octets_buffer, Encode::FB_CROAK) } catch { warn "Decoding failed: $_"; }
It is designed so that arguments can be in random order. Why do you want it like that? There is a configuration setting called
require_order
, but it is not exactly what you want..pl
indicates a Perl library, most like a collection of subroutines, ready to be included viarequire
. This is from more than 10 years ago. People on Windows also like to give this extension to plain Perl programs because the operating system is so much extension centric and does not work comfortably with files without extensions..pm
indicates a Perl module. A module is just a library that follows a few additional conventions. This is from the Perl 5 era.File::Copy
is translated to the file nameFile/Copy.pm
which is in one of the paths in your@INC
, for details again seerequire
. On my system it would be in/usr/lib/perl5
, e.g./usr/lib/perl5/5.10.0/File/Copy.pm
.