cOreey has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

is there a way how to tell getopts to return false, when duplicit parameters appear in @ARGV?

For example running Perl script with: <code> perl myscript.pl --input="input1" --input"input2"

I need it to "scream and shout", when duplicity like this occurs. But I seem not to be able to find any information regarding to this topic.

Any help appreciated, Thanks!

Replies are listed 'Best First'.
Re: getopts and duplicit params
by toolic (Bishop) on Mar 13, 2013 at 12:26 UTC
Re: getopts and duplicit params
by regexes (Hermit) on Mar 13, 2013 at 10:53 UTC
    If I'm not mistaken, getopts handles this already.. the last variable offered will overwrite the one before.
    In your example...

    --input="input1" will be overwritten by "--input="input2"

    In other words, only one parameter will be handed over.
      That's exactly what I'm trying to avoid. I need to end the script rather than overwriting by the last appearance of the param.
        That goes against the general philosophy of running stuff from a shell command line and allowing users to customize their defaults. Users are free to set up aliases with their most commonly used flags and allowing duplicate flags / taking that last flag allows them to still access all the command line options. Flags for default options exist for this reason.
Re: getopts and duplicit params (multiple / FormValidator::Simple::Validator::SINGLE )
by Anonymous Monk on Mar 14, 2013 at 01:51 UTC

    See also Getopt::Flex, Getopt::Valid, FormValidator::Simple, CGI, App::Cmd, App::CLI

    Kind of silly , but you could write

    #!/usr/bin/perl -- use strict; use warnings; use Data::Dump; use CGI; use Getopt::Long; use FormValidator::Simple; Fudge(qw[ -i 3 --input=6 --input=9 ]); Fudge('-i', '__FILE__' ); sub Fudge { local @ARGV = @_; my $query = CGI->new({}); my $queryer = sub { my( $name, $value ) = @_; my @vals = $query->param( $name ); $query->param( $name, $value, @vals ); return; }; GetOptions( 'input|i=s' => $queryer, ); my $rules = [ input => [ qw[ NOT_BLANK ASCII SINGLE ], ['REGEX' => qr/^\w+$/ +], ], ]; my $results = FormValidator::Simple->check( $query => $rules ); if ( $results->has_error ) { foreach my $key ( @{ $results->error() } ) { dd $results->record( $key )->data; foreach my $type ( @{ $results->error($key) } ) { print "invalid: $key - $type \n"; } print "\n"; } } else { print "valid input: ", $results->record('input')->data, "\n"; } } sub FormValidator::Simple::Validator::SINGLE { package FormValidator::Simple::Validator; my ($self, $params, $validatorArgs) = @_; my $data = $params->[0]; my $selected = ref $data ? $data : [$data]; return scalar(@$selected) == 1 ? TRUE : FALSE; } __END__ [9, 6, 3] invalid: input - SINGLE invalid: input - REGEX valid input: __FILE__

    SINGLE is "monkeypatched" instead of a plugin