How to create command line options in Perl

Home > Search > How-to
  by

Let's say you want to create a Perl script and allow users to pass options to the script. For example, perhaps you want to let people pass their name and occuption to the script, like this.

perl example.pl --name John --occuption programmer

 

First, import the Options module.

use Options;

 

Next, create the options and flags that you want to be able to use on the command line. An option must be followed by a value. In this example, the name option must be followed by a value (such as John) and the occupation option must be followed by a value (such as programmer). Flags will not contain any values.

The following script will allow users to use the -n or --name and -o or --occupation options when running the script.

my $options = new Options(params => [
  ['name',       'n', "", 'Name.'],
  ['occupation', 'o', "", 'Occupation.']
  ],
  flags =>  [
    ['dryrun', 'd', 'Do not make any changes, but show me what the script will do.'],
]);

my %argv = $options->get_options();

 

Create unique variables for each option. In this example, the $name variable will have a value of John, and the occupation variable will have a value of programmer.

my $name = lc($options->get_result('name'));
my $occupation= lc($options->get_result('occupation'));

 

If you want your script to not continue if an option does not contain a value, use if statements to exit the script.

# Exit if name is empty
if ($name eq ""){
  print "You didn't use the -n or --name option on the command line";
  exit(1);
}

# Exit if occupation is empty
if ($occupation eq ""){
  print "You didn't use the -o or --occuption option on the command line";
  exit(1);
}

 

You can now do something with the variables, such as printing them back to the console.

print "$name\n";
print "$occupation\n";

 


ARGV

Another option is to use the @ARGV array. In this example, the @ARGV array contains two variables, $first and $second.

my ($first, $second) = @ARGV;

 

When running the Perl script, the first string following the command will be loaded into the $first variable, nd the second string into the $second variable.

perl example.pl Hello World

 

Both variables can be printed using the @ARGV array. In this example, the @ARGV array will contain "Hello World".

print "@ARGV\n";

 

Or, each variable can be printed using $first and $second. In this example, the $first variable contains "Hello" and the $second variable contains "World".

print "$first\n";
print "$second\n";

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments