Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse command-line switches in Perl?

In order to extend my "grep" emulator in Perl I have added support for a -r switch which enables recursive searching in sub-directories. Now the command line invocation looks something like this:

perl pgrep.pl -r <directory> <expression>

Both -r and the directory arguments are optional (directory defaults to '.'). As of now I simply check if the first argument is -r and if yes set the appropriate flag, and scan in the rest two arguments using the shift operation. This obviously would be a problem if -r were to appear at the end of the argument list or worse still - in between the directory name and the search expression.

One workaround would be to simply delete the -r item from the @ARGV array so that I can simply shift-in the remaining arguments, but I can't figure out a way to do it without getting an 'undef' in an odd position in my array. Any suggestions or different strategies that you might have used are welcome.

like image 623
aks Avatar asked Nov 28 '22 00:11

aks


2 Answers

You should be using GetOpt::Long. This will do everything you need as described.

like image 115
dsm Avatar answered Dec 05 '22 17:12

dsm


use Getopt::Std;

our $opt_r; # will be set to its value if used.
getopts('r:'); # -r has an option.
like image 22
Brian Carlton Avatar answered Dec 05 '22 19:12

Brian Carlton