Processing Command Line Options with PERL - Opting In (Page 7 of 9 )
Getopt::Long.pm can also process command-line arguments containing multiple values, simply by storing all the values in a Perl array. Consider, for example, the following script, which is designed to add email addresses to a subscription list (maybe for an email newsletter?). Here, the user can send as many email addresses as (s)he likes to the script, simply by repeating the "--add" option with different values.
Take a look:
#!/usr/bin/perl
# import module
use Getopt::Long;
# read options
$result = GetOptions ("add=s" => @list);
# once all the values are in the array
# do something with them
# open file for writing
open(FILE, ">>subscribers.dat");
# iterate over array
foreach $l (@list)
{
# write array elements to file
print FILE "$ln";
print "Added $ln";
}
# close file when done
close (FILE);
Here's what the output might look like:
$ ./editlist.pl --add=me@me.com --add=you@you.com --add=them@them.com
Added me@me.com Added you@you.com Added them@them.com
What's In A Name?
Getopt::Long.pm also supports aliases for options, allowing you to provide users with an alternative, sometimes shorter way of accessing the same option. This is accomplished by placing alternative option names after the first one and separating the various alternatives with pipes (|). Consider the following example, which shows you how:
#!/usr/bin/perl
# import module
use Getopt::Long;
# read options
$result = GetOptions ("color|colour|c" => $color);
# print value
$color ? print "Colors are on" : print "Colors are off";
Here, you can attach any of the options "--color", "--colour", "--c" or
"-c" to the command line - Getopt::Long.pm will treat them all as one
and the same.
$ ./script.pl --color
Colors are on
$ ./script.pl --c
Colors are on
$ ./script.pl -c
Colors are on
$ ./script.pl --colour
Colors are on
Next: Negative Reinforcement >>
More Perl Articles
More By icarus, (c) Melonfire