perl intro 9 command line arguments

9
05/13/12 1 ATI Confidential Command Command Line Line Arguments Arguments Perl Brown Bag Shaun Griffith May 8, 2006

Upload: shaun-griffith

Post on 11-Jul-2015

862 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Perl Intro 9 Command Line Arguments

05/13/12 1ATI Confidential

Command Command LineLine

ArgumentsArguments

Perl Brown Bag

Shaun Griffith

May 8, 2006

Page 2: Perl Intro 9 Command Line Arguments

05/13/12 2

Agenda

TIMTOWTDI•Argument Types•DIY (Do It Yourself)•-s Builtin•Getopt::Long•Getopt::Declare

Page 3: Perl Intro 9 Command Line Arguments

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

Page 4: Perl Intro 9 Command Line Arguments

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

Page 5: Perl Intro 9 Command Line Arguments

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?

Page 6: Perl Intro 9 Command Line Arguments

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

Page 7: Perl Intro 9 Command Line Arguments

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

Page 8: Perl Intro 9 Command Line Arguments

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?)

Page 9: Perl Intro 9 Command Line Arguments

05/13/12 9

Next Time?

Suggestions?