Passing arguments from the command line in Perl

I used to do this for specifying the usage:

#!/usr/bin/perl

use strict;
use warnings;

my $usage = "$0: <infile.fa> <blah> <blah>\n";
my $a = shift or die $usage;
my $b = shift or die $usage;

#etc.

However this became a problem when I needed to pass the number “0” as an argument. So I thought I’ll improve the code via the Perl module Getopt::Std.


#!/usr/bin/perl

use strict;
use warnings;

use Getopt::Std;

my %opts = ();
getopts('f:b:g:e:h', \%opts);

if ($opts{'h'} || !keys %opts){
   usage();
}

print "Your options are:\n";
foreach my $opts (keys %opts){
   print "$opts\t$opts{$opts}\n";
}

exit(0);

sub usage {
print STDERR <<EOF;
Usage: $0 -f file -b 10 -g temp.file -e 20

Where:   -f test.txt            input file
         -b kdjaksd             b for bananas
         -g kdjf                more description
         -e 3                   blah blah blah
         -h                     this helpful usage message

EOF
exit;
}

__END__

Depending on how your script works, you can set up conditional checks (e.g. unless exists $opt{‘f’}) to see if essential arguments have been set or not.

Print Friendly, PDF & Email



Creative Commons License
This work is licensed under a Creative Commons
Attribution 4.0 International License
.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.