in reply to GetOpt ignore required arguments

It would really help if you showed some code and a specific situation.

"How to get getopt to ignore this field?"
Getopt already ignores what it does not understand. In the option string, you specify that an option takes an argument by the ':',semi-colon character. Getopt takes all of the stuff that it understands out of @ARGV and you process what it left over! In your case, sounds like exactly ONE thing should be left in @ARGV (see below). If you don't specify that an option needs an argument, then Getopt will leave the token after the option alone!

I show some examples that sound like they are close to your situation below. Having an "standalone" argument that looks like an option (-abc or whatever) is a very unusual situation. One way of dealing with this has been posted and there are others. Before rolling further down that rabbit hole, show us an actual example of your problem.

#!/usr/bin/perl -w use strict; use Getopt::Std; my %opts; my $usage = "usage: options [-a arga] [-b] mandatory_arg"; die "$usage \n" if !getopts("a:b", \%opts); die "error: arguments=".@ARGV." @ARGV\n$usage \n" if @ARGV !=1; print "ok\n"; __END__ # Wrong, "mandatory" used as -a's argument! C:\TEMP>option.pl -a mandatory error: arguments=0 usage: options [-a arga] [-b] mandatory_arg # Now ok! C:\TEMP>option -a arga mandatory ok # Error: b doesn't take an arg # looks like another mandatory arg! C:\TEMP>option -a -b arga mandatory error: arguments=2 arga mandatory usage: options [-a arga] [-b] mandatory_arg # -b doesn't expect an arg and that causes # error C:\TEMP>option.pl -b extra -a arga mandatory error: arguments=4 extra -a arga mandatory usage: options [-a arga] [-b] mandatory_arg # Now ok! C:\TEMP>option.pl -b -a arga mandatory ok

Replies are listed 'Best First'.
Re^2: GetOpt ignore required arguments
by stevensw (Acolyte) on Aug 22, 2011 at 17:54 UTC
    OK I should have clarified that some of my options have optional arguments, that is 0 or 1 or more. This presented a problem when you do something like this: cmd -option mandatory_arg When -option is allowed any number of arguments, including 0. However I think I fixed my problem using a variation of what linuxer told me, basically set the last argument in the ARGV array to "--" before GetOptions is called.
      Yes, the idea that an option like "-a" sometimes has an arg and sometimes not, does present problems...
      [ -a [optional_arg ] ] Here -a is optional and its arg is optional (if there is a -a option).

      I personally would try to organize the UI so that each -option either has >= 1 args or no args. But I'm happy that you have a solution that works for your case! Thanks for reporting back on what worked for you!