How to create command line options and flags in Perl

Home > Search > How-to
  by

An options object can be used to create both command line options and flags. An option must be followed by a value. In this example, the --name option is followed by a value of Jeremy.

~]# perl example.pl --name Jeremy

 

A flag is not followed by a value on the command line. In this example, the --help flag is used. .

~]# perl example.pl --help

 


Import the Options module.

use Options;

 

Create the options and flags that you want to be able to use on the command line. The following script has two options (name and occuption) and one flag (help).

my $options = new Options(params => [
  ['name',       'n', "", 'Name.'],
  ['occupation', 'o', "", 'Occupation.']
  ],
  flags =>  [
    ['help', 'h', 'Looks like you need some help.'],
]);

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 = $options->get_result('name');
my $occupation= $options->get_result('occupation');

 

Determine if a flag was used.

if ($options->get_result('help')){
  print "You would add your help menu text here";
}

 

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