perl5 icon indicating copy to clipboard operation
perl5 copied to clipboard

Getopt::Std questionable undefined value behaviour

Open XSven opened this issue 1 month ago • 5 comments

Module: Getopt::Std

In this issue I am referring to this piece of documentation

If an argument is expected but none is provided, $opt_x is set to an undefined value.

I could not find a corresponding test in lib/Getopt/Std.t that proves this. Instead I have found several tests that refer to the two-argument form of getopts(). One of them is

undef %opt;
my $expected;
{
    local @ARGV = ( '-a', '-b', 'foo', '-c' );
    getopts('ab:c:', \%opt);
    $expected = { 'a' => 1, 'b' => 'foo', 'c' => undef };
    is_deeply(\%opt, $expected,
        "getopts: multiple switches; switch expected argument, none provided; value undef");
    undef %opt;
}

Although this test and some others prove that the documentation is correct, they don't check the return value of the getopts() call, so I have added the assertion:

ok( getopts( 'ab:c:', \%opts ), 'getopts succeeded' );

But the assertion fails, but why? The documentation states:

The getopts() function returns true unless an invalid option was found.

What is the conclusion? Is an option that requires an option-argument like the above option "c" and that doesn't get an argument treated as an invalid option and at the same time gets the undef value assigned to it when the two-argument form of getopts() is used. Sorry I am confused.

XSven avatar Nov 08 '25 17:11 XSven