Search code examples
perlgetopt-long

Perl Getopt::Long - use subparameter only for defined parameter


I would like the --import parameter to have a "sub-parameter" that will only work on this parameter, nowhere else. Example:

app.pl --import --fresh

output: command working

app.pl --export

output: command working

app.pl --export --fresh

output: command not found

Can this be achieved by GetOpt::Long? Please, guide me a little.


Solution

  • I think that without resorting to partial parsing the closest you can get to with Getopt::Long is this:

    use strict;
    use warnings;
    use Data::Dumper;
    use Getopt::Long;
    
    GetOptions('export=s%{1,5}'=>\my %export, 'another_option=s'=>\my $ao);
    
    print Dumper({ 'export'=> \%export, 'another_option'=>$ao});
    

    perl t1.pl  --export fresh=1 b=2 c=3 --another_option value
    

    $VAR1 = {
              'export' => {
                            'c' => '3',
                            'b' => '2',
                            'fresh' => '1'
                          },
              'another_option' => 'value'
            };
    

    Here export=s%{1,5} parses --export fresh=1 b=2 c=3 into hash %export.
    s%{1,5} expects from 1 to 5 key=value pairs