Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl GetOpt::Long multiple arguments with optional parameter

this is my fist post on stackoverflow. :)

I'm trying to solve this scenario with GetOpt::Long.

./myscript -m /abc -m /bcd -t nfs -m /ecd -t nfs ...

-m is mount point and -t is type of file system (can be placed, but it is not mandatory).

  Getopt::Long::Configure("bundling");
  GetOptions('m:s@' => \$mount, 'mountpoint:s@' => \$mount,
             't:s@' => \$fstype, 'fstype:s@'  => \$fstype)

This is not right, i'm not able pair proper mount and fstype

./check_mount.pl -m /abc -m /bcd -t nfs -m /ecd -t nfs
$VAR1 = [
          '/abc',
          '/bcd',
          '/ecd'
        ];
$VAR1 = [
          'nfs',
          'nfs'
        ];

I need fill unspecified fstype e.g. with "undef" value. the best solution for me would be get hash such as...

%opts;
$opts{'abc'} => 'undef'
$opts{'bcd'} => 'nfs'
$opts{'ecd'} => 'nfs'

Is it possible? Thank you.

like image 990
Milan Čížek Avatar asked Mar 15 '26 05:03

Milan Čížek


1 Answers

This won't be easy to do with Getopt::Long directly, but if you can change the argument structure a bit, such as to

./script.pl --disk /abc --disk /mno=nfs -d /xyz=nfs

...the following will get you to where you want to be (note that a missing type will appear as the empty string, not undef):

use warnings;
use strict;

use Data::Dumper;
use Getopt::Long;

my %disks;

GetOptions(
    'd|disk:s' => \%disks, # this allows both -d and --disk to work
);

print Dumper \%disks;

Output:

$VAR1 = {
          '/abc' => '',
          '/mno' => 'nfs',
          '/xyz' => 'nfs'
        };
like image 103
stevieb Avatar answered Mar 17 '26 21:03

stevieb