Search code examples
perloptional-arguments

Read optional command-line arguments in Perl


I am new to Perl and I'm confused with its handling of optional arguments.

If I have a perl script that's invoked with something along the lines of:

plgrep [-f] < perl regular expression > < file/directory list > 

How would I determine whether or not the -f operator is given or not on the command line?


Solution

  • All of the parameters passed to your program appear in the array @ARGV, so you can simply check whether any of the array elements contain the string -f

    But if you are writing a program that uses many different options in combination, you may find it simpler to use the Getopt::Long module, which allows you to specify which parameters are optional, which take values, whether there are multiple synonynms for an option etc.

    A call to GetOptions allows you to specify the parameters that your program expects, and will remove from @ARGV any that appear in the command line, saving indicators in simple Perl variables that reflect which were provided and what values, if any, they had

    For instance, in the simple case that you describe, you could write your code like this

    use strict;
    use warnings 'all';
    use feature 'say';
    
    use Getopt::Long;
    use Data::Dump;
    
    say "\nBefore GetOptions";
    dd \@ARGV;
    
    GetOptions( f => \my $f_option);
    
    say "\nAfter GetOptions";
    dd $f_option;
    dd \@ARGV;
    

    output

    Before GetOptions
    ["-f", "regexp", "file"]
    
    After GetOptions
    1
    ["regexp", "file"]
    

    So you can see that before the call to GetOptions, @ARGV contains all of the data in the command line. But afterwards, the -f has been removed and variable $f_option is set to 1 to indicate that the option was specified