开发者

Getting command line options and their values

开发者 https://www.devze.com 2023-02-09 17:47 出处:网络
I want to log options and their arguments from user command after running the script. Consider this command:

I want to log options and their arguments from user command after running the script.

Consider this command:

./test.pl --ip localhost --id 400154 --class firstgrade 

...and many other options and values. My desired output would be like this(by using log4perl):

debug - ip开发者_C百科=>localhost id=>400154 class=>firstgrade 

I do:

use Getopt::Long; 
my $ip;
my $id; 
my $class;
my %h =('ip' => \$ip,
        'id' => \$id,
    'class' => \$class);
GetOptions(\%h);
$logger->debug(join('=>',%h));

but it doesn't work. Please help.


Your code is weird combination of two distinct features of Getopt::Long - it can either parse options into hash or fill individual options into variables. It is even possible to put part into hash and rest into variables.

This should work:

use Getopt::Long;

my @options = qw(ip id class);
my %h = ();
GetOptions(\%h,
    map { "$_:s" } @options
) or die "Could not parse";
warn map { "$_=>$h{$_} " } keys %h;

This is variant where parsed options are put into the hash. Note :s after each option to indicate that it takes an argument.

Edit: updated the answer per clarification below.


Try this:

my $ip = ""; my $id = ""; my $class= "";
GetOptions('ip=s' => \$ip, 'id=s' => \$id, 'class=s' => \$class);
print "debug - ip=>$ip id=>$id, class=>$class";

And you should probably call it like this:

./test.pl --ip localhost --id 400154 --class firstgrade


The following code demonstrates two ways to achieve what you want.

The 'home grown' method uses map and join to generate the options list. (The grep eliminates undef options. You can remove the grep {} part.)

The Data::Dumper method may be desirable because it's eval-able.


#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long qw(:config gnu_getopt);
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent = 0;
$Data::Dumper::Terse = 1;

my %opts = (
  dir => undef,
  verbose => 0,
  silent => 0,
 );

GetOptions(\%opts,
           'dir|d=s',
           'verbose|v+',
           'silent+',
          )
  or die("Usage: blah\n");

# also see Getopt::Long perldoc for pod2usage

print( "home grown:\n",
       join(" ", map { sprintf('%s=>%s',$_,$opts{$_}||'undef') } 
              grep {defined $opts{$_}} keys %opts ),
       "\n" );

print( "Dumper:\n",
       Dumper(\%opts), 
       "\n" );

Example:

apt12j$ ~/tmp/x.pl  -vv --silent
home grown:
verbose=>2 silent=>1
Dumper:
{'dir' => undef,'silent' => 1,'verbose' => 2}


Checkout MooseX::Getopt, it'll help you two-fold:

  1. get you into modern OO perl

  2. create super simple command line apps.

Checkout MooseX::App::Cmd. It'll help you separate your logic out as well. Or App::Cmd if you don't want to drink the Moose kool-aid just yet.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号