Link to home
Start Free TrialLog in
Avatar of abgtemp
abgtempFlag for United States of America

asked on

Perl Script with Command Line Options

I need help creating a Perl script that will accept command line switches using a dash to distinguish the switch.

example:
myscript.pl -n var1 -b var2
ASKER CERTIFIED SOLUTION
Avatar of johnsone
johnsone
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can do this with argv, just as with C code.

http://www.cyberciti.biz/faq/howto-pass-perl-command-line-arguments/

You can also enable perl auto-parsing of command line flags, which will set variables, by using the -s switch.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Use Getopt::Long it's a core module and very flexible.
I assume this is what you want:

-aLabel=aData -bLabel=bData -cLabel=cData -dLabel="d data"

foreach $arg (@ARGV) {
	($aLabel,$aData) = split (/\=/,$arg); 
	$pArgs{$aLabel}  = $aData; 
}

Open in new window


This will give you a nice hash with your arguments and options easily accessible.  Enjoy.
Avatar of abgtemp

ASKER

Having not worked with perl, it would have been nice if an example was provided when referencing getopt
The Getopt::Long module I linked to provides several examples.  If you needed more explanation, we would have been happy to provide more examples and explanations.