in reply to Getopt - Validate arguments before processing
interesting question: I was sure Getopt::Long was consuming the @ARGV array so you had the possibility to check if something unkonow is still there.. but is too late for this when it arrives the moment and "Processing sub first" is already fired.
Then I read about die("!FINISH") special behaviour, but is not useful.. again it fires too late.. so you must move quick to intercept the unkonown option.
A BEGIN block does the trick (but I moved the help sub on top, so it is parsed before the BEGIN block, so it can be called: you must move other subs to give them a chance to be called):
use warnings; use strict; use Getopt::Long; sub help { print "Available options are: \n"; print "\t--first\n"; print "\t--help\n"; } BEGIN{ # no warnings; #strangely this is not able to suppress the warning + "Undefined subroutine &main::first called at.." GetOptions( 'first' => \&first, 'help' => \&help, ) or &help and die "Invalid options passed to $0\n" } sub first { print "Processing sub first\n"; } __END__ perl getoptcheck.pl --year --first Unknown option: year Undefined subroutine &main::first called at ..perl5.26.64bit/perl/lib/ +Getopt/Long.pm line 606. Available options are: --first --second --help Invalid options passed to getoptcheck.pl BEGIN failed--compilation aborted at getoptcheck.pl line 20.
L*
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Getopt - Validate arguments before processing -- BEGIN
by Corion (Patriarch) on Jan 31, 2022 at 08:59 UTC | |
by Discipulus (Canon) on Jan 31, 2022 at 09:03 UTC | |
by ikegami (Patriarch) on Jan 31, 2022 at 14:44 UTC | |
Re^2: Getopt - Validate arguments before processing -- BEGIN
by soonix (Chancellor) on Jan 31, 2022 at 20:30 UTC |