Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials

parsing command line parameters with Getopt::Long

( categories: )

Getopt::Long is a very powerful module which gives you a great deal of control over command line arguments.

To use this module, you specify the type of command line parameters you expect to receive using the function GetOptions(). GetOptions() will return a true value if the command line arguments could be processed successfully; otherwise it will print an appropriate error message to STDERR and return false.

By default, the arguments are not case sensitive, could start with either a single (-) or a double (--) dash and may be abbreviated to uniqueness.


Here are some usage examples:

-- arguments with no values (example: "program --debug")

GetOptions('debug' => \$variable);


extending the library path

( categories: | )

By default perl looks for modules in the standard library path and the current directory. Sometimes you need to use some modules that are installed in non standard locations; there are several ways to deal with this situation:

-- Install the module somewhere in the standard library path

If you have administrator privileges, then the best solution is to install the modules in any of the system defined library paths (you can get the paths executing perl -le 'print foreach @INC').

-- Set the environment variable PERL5LIB

Perl will look for modules in the directories specified in PERL5LIB environment variable before looking in the standard library and current directory, so you can set this variable to locate your modules.


check the number of arguments passed to a script

( categories: )

Use the @ARGV array in scalar context

Example:
if ( @ARGV > 0 )
{
  print "Number of arguments: " . scalar @ARGV . "\n";
}
else
{
  print "No arguments!\n";
}


Syndicate content