Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Examples for using Getopt::Long

by bahadur (Sexton)
on May 09, 2005 at 12:43 UTC ( #455158=perlquestion: print w/replies, xml ) Need Help??
bahadur has asked for the wisdom of the Perl Monks concerning the following question:

thanks for the replies this is what i dont get
my $data = "file.dat"; my $length = 24; my $verbose; $result = GetOptions ("length=i" => \$length, # numeric "file=s" => \$data, # string "verbose" => \$verbose); # flag
why do we need to create variables like data and length when the arguments will be passed from command line. here is what i want to do. take -u user name, -p password, -s hostname:portnumber from the command like and then how will they be used with this module? how can this parser help me in parsing the above mentioned command line arguments. p.s: after recieving them from the command like i ll send the user name pasword for validation to the host given on the command like. so like i want to know how using this parser will be more helpful in parsing the command line arguments. and how it will be more difficult with out using the parser?

Retitled by Steve_p from 'Getopt::Long'.

Replies are listed 'Best First'.
Re: Examples for using Getopt::Long
by Joost (Canon) on May 09, 2005 at 13:33 UTC
    update: since the OP replaced his original question, the answer below doesn't make much sense.

    There is an example snippet right at the top of the module's documentation:
    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

    This will set the $length, $data and $verbose variables according to the --length (with integer value), --file (with string value) and --verbose (boolean switch) options passed to the script.

    Getopt::Long does indeed have only one public function in its API, because you don't need more than one function. Your statement that every Java API has more than one method is wrong: here's one with only 1 method

    A module is just perl code in a file that has a .pm extension. It doesn't even have to have any public methods/functions.

    See perlmod and perlmodlib for much more info about using and creating modules.

Re: Examples for using Getopt::Long
by mpeters (Chaplain) on May 09, 2005 at 13:44 UTC
    a simple example:
    #!/usr/bin/perl use strict; use Getopt::Long; # setup my defaults my $name = 'Bob'; my $age = 26; my $employed = 0; my $help = 0; GetOptions( 'name=s' => \$name, 'age=i' => \$age, 'employed!' => \$employed, 'help!' => \$help, ) or die "Incorrect usage!\n"; if( $help ) { print "Common on, it's really not that hard.\n"; } else { print "My name is $name.\n"; print "I am $age years old.\n"; print "I am currently " . ($employed ? '' : 'un') . "employed.\n"; }
    as a programmer from C and Java i have this view that every API has several functions/methods in it. but inside this module i have found only one function. can any one explain what a module is and why does it only contain one function.
    Just because Getopt::Long only has one major function doesn't mean it's not worthy of being it's own module. There are plenty of features of that one function (GetOptions) that give it plenty to document. I don't see this as a C/Java vs Perl thing, just the desire to keep it simple, small, useful and resuable.

Re: Examples for using Getopt::Long
by ww (Archbishop) on May 09, 2005 at 14:10 UTC
    bahadur:

    Please do NOT replace an entire question with an (un-labeled) update, as you have done here.

    Later readers may be able to infer the original question in this case, but generally, either add a plainly labeled update, or reply to a responder, so future visitors can follow the thread.

    note to the (presumed) future reader: Loosely translated, and imperfectly recalled, bahadur sought wisdom on how to use the Getopt::Long module (had not discovered the pod, apparently) and questioned meaning of "module" with but a single function (as contrasted to C and java's multi-function counterparts)

    You probably should stress my note above, "imperfectly recalled."

Re: Examples for using Getopt::Long
by thcsoft (Monk) on May 09, 2005 at 13:19 UTC
    the module in question bears its own pod code. so just type: pod2html Long.pm > Long.html

    language is a virus from outer space.
Re: Examples for using Getopt::Long
by ikegami (Pope) on May 09, 2005 at 15:29 UTC

    (Here's an answer to the updated question.)

    why do we need to create variables like data and length when the arguments will be passed from command line.

    Those were just an example. Instead, you'd call your variables something like $user, $passwd, etc.

    use Getopt::Long (); sub usage { my $message = $_[0]; if (defined $message && length $message) { $message .= "\n" unless $message =~ /\n$/; } my $command = $0; $command =~ s#^.*/##; print STDERR ( $message, "usage: $command -u username [-p password] -s hostname:port\n" . " ...\n" . " ...\n" . " ...\n" ); die("\n") } my $user; my $passwd; my $host; my $port; Getopt::Long::GetOptions( 'u=s' => \$user, 'p=s' => \$passwd, 's=s' => sub { local *_ = \$_[1]; /^([^:]+):(\d+)$/ or die("Invalid format for option s.\n"); $host = $1; $port = $2; }, ) or usage("Invalid commmand line options."); usage("The user name must be specified.") unless defined $user; usage("The server hostname and port must be specified.") unless defined $host; if (!defined $passwd) { # Prompt for password here... }
      hi can u plz explain this piece of code
      Getopt::Long::GetOptions( 'u=s' => \$user, 'p=s' => \$passwd, 's=s' => sub { local *_ = \$_[1]; /^([^:]+):(\d+)$/ or die("Invalid format for option s.\n"); $host = $1; $port = $2;},)
      specially the place u=s =>$user

        Of course this all completely and thoroughly described in the Getopt::Long documentation and I really think you should spend a bit more time reading it yourself than asking questions here, however it is quite simply really: GetOptions gets passed a hash describing the options for the program that are to be passed: the key is the option itself with an optional type and the value is a reference to a variable which will receive the value of the option. So in the case of the  'u=s' => \$user you have an option -u which is a string and who's value will be placed in the variable $user. The options are parsed and placed in the appropriate variables when GetOptions is called - this is why the module only requires the single function.

        /J\

Re: Examples for using Getopt::Long
by graff (Chancellor) on May 10, 2005 at 04:00 UTC
    i want to know how using this parser will be more helpful in parsing the command line arguments. and how it will be more difficult with out using the parser?
    ikegami's example is more verbose and detailed than the typical usage for Getopt::Long, so it might not make the best answer to "how does this module make things easier for me?" :P

    As a matter of habit, if you write a lot of command-line scripts that tend to make frequent use of multiple options, you're either going to use Getopt::Long (or Getopt::Std, which would be a bit simpler to use and just as good for your stated needs), or you're going to write some variation on the same "while ( @ARGV and ... )" loop in every script.

    For me, it was a matter of realizing how tedious it is to (re)write that while loop every time. If I just want this one script to support options "-u user", "-p passwd", "-h host:port", and some other script to support "-f foo", "-b bar", "-z baz", somehow it seems easier for the scripts to have:

    use Getopt::Std; my $Usage = "Usage: $0 -u user -p passwd -h host:port\n" # or "$0 -f foo -b bar -z baz" for some other script # hash to hold option flags, default values: my %opt = ( u => 'me', p => 'secret', h => 'localhost:80' ); my $opts = join '', keys %opt; die $Usage unless ( getopt( $opts, \%opt ) and $opt{u} =~ /\w/ and $opt{p} =~ /\S/ and $opt{h} =~ /\w:\d+$/ ); # adjust or skip the sanity checks as you please
    Getopt::Std has an additional method (getopts, as opposed to getopt), which lets you differentiate between options that require args vs. options that set boolean values (e.g. "-v" to turn on "verbose mode").

    Getopt::Long provides more flexibility for argument checking (being clear about options that take strings vs. numerics vs. no args) and option structure (allowing multivalued options returned as arrays of values -- e.g. "--add this --add that --add the_other"). But Getopt::Std works fine for most cases.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://455158]
Approved by Corion
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2017-08-19 12:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Who is your favorite scientist and why?



























    Results (310 votes). Check out past polls.

    Notices?