Leo
Leo

Reputation: 189

Command line arguments with keywords

I am passing the command line arguments to a Perl script and retrieving it via ARGS[0].

perl <perlscript.pl> windows IE.

I would like to give keywords to the values mentioned above.

perl <perlscript.pl> -os windows -browser IE -instance 2.

There might be times where instance might or might not be present. How do I go about handling this in my Perl script?

Upvotes: 2

Views: 288

Answers (2)

Hunter McMillen
Hunter McMillen

Reputation: 61515

There are several modules for handling command line arguments: Getopt::Declare and Getopt::Long are probably the most popular. At my work we mainly use Getopt::Declare so Ill show and example of that since @toolic covered Getopt::Long.

my $ARGS = Getopt::Declare->new(
   join("\n", 
        "[strict]",
        "-os       <string> The operating system [required]",
        "-browser  <string> The web browser      [required]",
        "-instance <int>    The instance"
   ) 
) or die;

Now you can access any of the parmeters via the $ARGS hash. i.e. $ARGS->{-os}

[strict] parses the command line strictly and reports any errors.

[required] after an option declaration means that field must be there, note I left it off of instance.

Upvotes: 3

toolic
toolic

Reputation: 62002

Use Getopt::Long and store your options in a hash:

use warnings;
use strict;
use Getopt::Long qw(GetOptions);

my %opt;
GetOptions(\%opt, qw(
    os=s
    browser=s
    instance=i
)) or die;

Upvotes: 6

Related Questions