Perl Command-Line Arguments

From Wiki
Jump to navigation Jump to search

The @ARGV array

With Perl, command-line arguments are stored in the array named @ARGV. $ARGV[0] contains the first argument, $ARGV[1] contains the second, etc.

The Getopt::Std and Getopt::Long Modules

#!/usr/bin/perl
use Getopt::Long;
GetOptions("o"=>\$oflag,
    "verbose!"=>\$verboseornoverbose,
    "string=s"=>\$stringmandatory,
    "optional:s",\$optionalstring,
    "int=i"=> \$mandatoryinteger,
    "optint:i"=> \$optionalinteger,
    "float=f"=> \$mandatoryfloat,
    "optfloat:f"=> \$optionalfloat);
print "oflag $oflag\n" if $oflag;
print "verboseornoverbose $verboseornoverbose\n" if $verboseornoverbose;
...
print "Unprocessed by Getopt::Long\n" if $ARGV[0];
foreach (@ARGV) {
    print "$_\n";
}

Diamond Operator

If the command line arguments are a list of files that you want to read through, use the diamond operator to read through each one sequentially:

while (<>){
    chomp;  # operates on $_
    # do something with the current line in $_
}

Call it like this:

./my_program file1 file2 file3

or like this:

./my_program file*

It reads each file line by line, giving an error if a file can't be opened.

User Input from the Command Line

print "Enter your name: ";
chomp( my $name = <STDIN>);
print "Hello, $name!\n"