how to get command line options in perl
There are various ways to get command line options in perl.
The idea here is you write a script, and you want to call it like a regular command as you would ls, or find.
Basic intro
Here’s a simple script that takes user command line arguments and does something with it:
#!/usr/bin/perl
print "Hello, you said .. \n";
for ( @ARGV ){
print "$_\n";
}
What does this do?
Well, if you call it as:
perl script.pl this is it
It will print
Hello, you said .. this is it
Basically the special variable @ARGV holds command line arguments. This is also true under use strict. Same as with with %ENV, like $ENV{HOME} etc.
Something more interesting
What we really want is to conform to POSIX standards and parse arguents like find, with options and flags.
We want the above script to print out name and age for example, we want to be able to say:
perl script.pl -n leo -a 33
So let’s rewrite the script..
#!/usr/bin/perl
use strict;
use Getopt::Std;
my %o;
getopts('a:n:',\%o);
print "Hello, $o{n}, your age is $o{a}.\n";
print "Notice that now, the special vairable ARTV is empy: '@ARGV'";
Full documentation of Getopt::Std explains why we say getopts(’a:n:’).
Basically a: means that we expect a value, simply saying a would mean it’s a boolean, that if the user said -a, it means a is true.
Why is @ARGV empty afterwards? Because getops() will take the arguments out, only the ones specified for, in this case -a and -n.
What if you had more arguments?
Then they remain. That means you can combine, maybe you want to say that you expect -n and -a to be values, and anything else are .. words to
be printed onto the screen. Let’s try that.
Options and arguments left over
#!/usr/bin/perl
use strict;
use Getopt::Std;
my %o;
getopts('a:n:',\%o);
print "Hello, $o{n}, your age is $o{a}.\n";
print "You said .. \n";
for ( @ARGV ){
print "$_\n";
}
So, we would use this as..
perl script.pl -n leo -a 33 these are the words.
And it would print out:
Hello, leo, your are is 33 You said .. these are words
Easier even solution
Now, I don’t know about you, but this way of callng options annoys me to no end. So I wrote Getopt::Std::Strict
Which lets you rewrite the above as:
#!/usr/bin/perl
use strict;
use Getopt::Std::Strict 'a:n:';
print "Hello, $opt_n, your age is $opt_a.\n";
print "You said .. \n";
for ( @ARGV ){
print "$_\n";
}
Try it out, I hope you like it.
