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

I wish arg parser can put same option's args into an array like this;
use Getopt::xxx; getopts('e:'; \%options); if (ref $options{e} eq 'ARRAY'){ print 'you got e args with', $options{e}->@*; }else { print 'your e arg is ', $options{e} }
I can run like myscript.pl -e 'a' -e 'b' to get 'you got e args with a b'.what module is designed to do such thing.

ADDED

I write my own argparser to keep order and add same option args:)

my $all_options = "xp:b:f:s:"; my @s_options = $all_options =~ /[^:](?=:)/g; my @n_options = $all_options =~ /[^:](?!:)/g; my (@options, %options, $need); sub parsearg($$){ my ($index, $arg) = @_; if ($arg !~ /^-/){ return 1 if $index ne $need; } foreach (@s_options){ if ( $arg eq '-'.$_){ push @options, [$_, $ARGV[$index + 1]]; $need = $index + 1; return 0 } } foreach (@n_options){ if ($arg eq '-'.$_){ $options{$_} = 1; $need = $index; return 0 } } } while (my ($index, $argv) = each @ARGV){ last if parsearg $index, $argv; } my @files = splice @ARGV, $need + 1;

Replies are listed 'Best First'.
Re: how to argparse same option to array instead of overwrite
by ikegami (Patriarch) on Jul 09, 2024 at 06:49 UTC

    Getopt::Long has this functionality. See "Options with multiple values".

      yeah, how can I miss this
Re: Closed:how to argparse same option to array instead of overwrite
by ikegami (Patriarch) on Jul 09, 2024 at 13:42 UTC

    Why do you think Getopt::Long doesn't keep order? It would be better to use that instead of the buggy code you posted.

      humbly ask, how? since It assign args to different scalar, I want keep order globally. can you give me an example code then?
        #!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11160457 use warnings; use Getopt::Long; $SIG{__WARN__} = sub { die @_ }; @ARGV = qw( --foo 123 --bar 456 --foo 789 something extra ); use Data::Dump 'dd'; dd '@ARGV before', \@ARGV; my @fooarray; my @bararray; GetOptions 'foo=s' => \@fooarray, 'bar=s' => \@bararray; use Data::Dump 'dd'; dd 'fooarray', \@fooarray; use Data::Dump 'dd'; dd 'bararray', \@bararray; use Data::Dump 'dd'; dd '@ARGV after', \@ARGV;

        Outputs:

        ( "\@ARGV before", ["--foo", 123, "--bar", 456, "--foo", 789, "something", "extra"], ) ("fooarray", [123, 789]) ("bararray", [456]) ("\@ARGV after", ["something", "extra"])

        Ah, I misread. You are completely misusing options. You should provide a better interface.