FreeKB - How to create command line options and flags in Perl
How to create command line options and flags in Perl

Home > Search > How-to


Let's say you want to be able to use options and flags with one of your Perl scripts. In this example, the --name option is followed by a value of Jeremy.

perl example.pl --name Jeremy

 

In this example, the --help flag is used.

perl example.pl --help

 


The Options module can be used to provide support for command line options and flags. 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();

 

You can now use if statements to do something when an option or flag is used.

if ($options->get_result('name') eq ""){
  print "You didn't use the -n or --name option on the command line";
}

 

Likewise, you can check to see if an option or flag is defined.

if (defined $help) { print "the help flag is defined\n"; }

 

Often, a variable is defined that contains the value passed to the option. In this example, the $name variable will contain whatever value follows the --name option on the command line.

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

 

This is a common if statement for the --help flag.

if ($options->get_result('help')){
  $options->print_usage();
  exit 0;
}

 


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 62fcc in the box below so that we can be sure you are a human.




Comments