As you can see based upon the execution of the code, Getopt is processing the arguments as they are received. ... What I would like to accomplish is if any invalid argument is passed, immediatly display the help and exit the script without processing any arguments
In this example, what are sub first and second actually doing? Because if they have any side effects other than simply saving the fact that the option value was passed to the program, then I think you're not using the module as intended.
Update: Here's another variation, and my suspicion is that this may come closest to your original intent:
use warnings;
use strict;
use Getopt::Long;
my @actions;
GetOptions(
first => sub { push @actions, \&first },
second => sub { push @actions, \&second },
) or die "Invalid options passed to $0\n";
sub first {
print "Processing sub first\n";
}
sub second {
print "Processing sub second\n";
}
$_->() for @actions;
__END__
$ perl 11140961c.pl --first --second --first --second --second --first
Processing sub first
Processing sub second
Processing sub first
Processing sub second
Processing sub second
Processing sub first
$ perl 11140961c.pl --first --second --year --first --second --second
+--first
Unknown option: year
Invalid options passed to 11140961c.pl
/Update
One way to use the module with code references is the following, where in this example sub first and second are of course pretty simplistic and you'd be better off just using the normal boolean options provided by the module:
use warnings;
use strict;
use Getopt::Long;
my $do_first = 0;
sub first { $do_first = 1 }
my $do_second = 0;
sub second { $do_second = 1 }
GetOptions(first=>\&first, second=>\&second)
or die "Invalid options passed to $0\n";
if ($do_first) { print "First!\n" }
if ($do_second) { print "Second!\n" }
__END__
$ perl 11140961.pl --first --second --first --second --second --first
First!
Second!
$ perl 11140961.pl --first --second --year --first --second --second -
+-first
Unknown option: year
Invalid options passed to 11140961.pl
And if your intent is for these options to be processed in some kind of sequential way, here's one way to do that:
use warnings;
use strict;
use Getopt::Long;
my @actions;
sub first { push @actions, 'first' }
sub second { push @actions, 'second' }
GetOptions(first=>\&first, second=>\&second)
or die "Invalid options passed to $0\n";
for my $act (@actions) {
if ($act eq 'first')
{ print "First!\n" }
elsif ($act eq 'second')
{ print "Second!\n" }
else { die $act } # shouldn't happen
}
__END__
$ perl 11140961b.pl --first --second --first --second --second --first
First!
Second!
First!
Second!
Second!
First!
$ perl 11140961b.pl --first --second --year --first --second --second
+--first
Unknown option: year
Invalid options passed to 11140961b.pl
It would even be possible to populate @actions with code references and then simply call those instead of using string eq. see update above