perldefaultgetopt-long

Getopt::Long: Detect if no Options Passed


How to detect if no options were passed to a script using the GetOpt::Long module?

For instance to output script usage (help) with pod2usage() by default (when the script is called without options).

This general solution doesn't work (because options are not considered arguments):

if (@ARGV == 0) {
  ...
}

I found a related question that was asked 10 years ago, but it seems to be ambiguous (module not specified [ though looks like to be Getopt::Std ], the case with subroutine runs asked specifically), poorly written, and closed.

Best way to run subroutine if no options provided? Perl getOpt


Tried to read on return values:

https://perldoc.perl.org/Getopt::Long#Return-values-and-Errors

Tried to do via @ARGV == 0 as indicated above


Solution

  • Based on the answers and further reading elsewhere:

    I set my current solution to the following code snippet:

    use Getopt::Long;
    use Pod::Usage;
    
    my $options;
    
    my $argv_before_options = @ARGV; # Record somewhere
    
    Getopt::Long::Parser
      -> new( config => [ 'bundling', 'no_ignore_case' ] )
        -> getoptions(
            'quite|q' => \$options{quite},
            'help|h' => \$options{help},
           );
    
    my $argv_after_options = @ARGV; # Record for readability
    
    my $options_not_specified =
      $argv_after_getopts == $argv_before_getopts; # Boolean, holding as a variable for readability
    
    if ($options_not_specified or $options{help}) { # Default or -h
      pod2usage();
    }
    
    

    Which I'm satisfied about, although wishing Getopt-Long could have this detection built-in as a return value of some of its method.

    Maybe, it's time for a new PR?