perl intro 9 command line arguments
TRANSCRIPT
05/13/12 1ATI Confidential
Command Command LineLine
ArgumentsArguments
Perl Brown Bag
Shaun Griffith
May 8, 2006
05/13/12 2
Agenda
TIMTOWTDI•Argument Types•DIY (Do It Yourself)•-s Builtin•Getopt::Long•Getopt::Declare
05/13/12 3
Argument Types
What kinds of arguments to expect?-xyz toggle switch-xyz 17 value-xyz=17 value (parsing)-wx combined (-w –x)-x 17 24 list--x turn off--long double dash value bare value-- end of arguments
Where are the arguments?@ARGV
05/13/12 4
Criteria for Solution?
What do we want a solution to accomplish?
• Easy to use• Argument validation
• integers• file names
• Self-documenting• Usage statement (help)• Flexible• Powerful
05/13/12 5
Do It Yourself
Handle arguments manuallywhile (@ARGV){ my $argv = shift(@ARGV); if ($argv =~ /^-x$/){$x=1;next} if ($argv =~ /^-y$/) { $y = shift(@ARGV) or die; next; } if ($argv =~ /^--$/) { last } # stop push @files, $argv;}@ARGV = (@files, @ARGV);while (<>){ do something here }
Pros: full controlCons: tedious, check arguments manually documentation? extensibility?
05/13/12 6
-s Option
Perl has a builtin option for basic argument handling: -s
In the script, use it on the shebang line:#!/usr/local/bin/perl –s
…enabling this behavior:VariablesOption
$xyz = “blue”-xyz=blue
$xyz = 1-xyz
Pros: easyCons: documentation? shebang combined options? check arguments manually
05/13/12 7
Getopt::Long
use Getopt::Long;my $data = "file.dat"; my $length = 24; my $verbose;$result = GetOptions (
"length=i" => \$length, # numeric "file=s" => \$data, # string "verbose" => \$verbose # flag
);Pros: argument checkingCons: 24 pages of docs for G:L script documentation? wordy
05/13/12 8
Getopt::Declare
use Getopt::Declare;my $spec = qq{
[nocase] # case insenstive options-in <in:if> input file-out <out:of> output file[mutex –in –out]-off <offset:i> offset (int)-b[ells+]w[histles] -bw also works{ $::BELLS = 1; } }
my $options = Getopt::Declare->new($spec);Pros: Functionality! Spec is usage Argument checking Full Parser!Cons: Functionality! 32 pages of docs for G:D! Subtle gotchas (like []) Object oriented (more work?)
05/13/12 9
Next Time?
Suggestions?