Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: hmm - - - something has changed in perl (from 5.34 to 5.36

by choroba (Cardinal)
on Nov 23, 2022 at 17:35 UTC ( [id://11148331] : note . print w/replies, xml ) Need Help??

in reply to hmm - - - something has changed in perl (from 5.34 to 5.36

I'm getting the same error in 5.26. What works is to use -B4 (i.e. no space).


$before = shift @ARGV assigns the first element of @ARGV to $before. The first element is -B, regardless of the Perl version. Also, changing the array you're currently iterating over doesn't seem to be a safe operation.

How to fix?

Iterate over the indices rather than elements if you want to peek into surrounding elements.
my $before; my $arg_index = 0; while ($arg_index < $#ARGV) { my $arg = $ARGV[$arg_index]; if( $arg =~ /^-B(\d+)$/ ) { # months Before $before = $1; } elsif( $arg =~ /^-B$/ ) { $before = $ARGV[++$arg_index]; if( $before !~ /^\d+/ ) { die "Bad before argument ($before)\n"; } } } continue { ++$arg_index; }

Note that the code doesn't report "Bad before" if there's no space after -B but the value is not a number.

How to fix properly?

Use Getopt::Long.

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: hmm - - - something has changed in perl (from 5.34 to 5.36
by Tux (Canon) on Nov 24, 2022 at 10:12 UTC

    100% agree with this! And Getopt::Long is extremely easy:

    use 5.026000; use warnings; use Getopt::Long; GetOptions ( "B|before=i" => \my $before, # An integer argument is required ) or die "User-friendly message\n");

    And if you want -B without any argument to default to say 42, all you have to change is

    GetOptions ( "B|before:42" => \my $before, # An integer argument is optional an +d defaults to 42 when -B used without arg ) or die "User-friendly message\n");

    One step further: set a default, and also give a different default for -B without argument

    GetOptions ( "B|before:42" => \(my $before = 2), ) or die "User-friendly message\n");

    In the first two examples $before will have the value undef when the option -B is not given at all. In the last example the default will be 2.

    Enjoy, Have FUN! H.Merijn