neilwatson has asked for the wisdom of the Perl Monks concerning the following question:

Greetings,

I'm having trouble parsing args from an array. Consider this code:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Getopt::Long 'GetOptionsFromArray'; use feature 'say'; my @args = @ARGV; my %query_params; print "perl args: ".Dumper( \@args ); GetOptionsFromArray ( \@args, \%query_params, 'timestamp' ); print "query_params: ".Dumper( \%query_params ); my $report_type = $args[0]; say "timestamp = $query_params{timestamp}"; say "report type = $report_type"

Results:

./foo.pl class myclass -t 2014-09-08:14:00T-004 perl args: $VAR1 = [ 'class', 'myclass', '-t', '2014-09-08:14:00T-004' ]; query_params: $VAR1 = { 'timestamp' => 1 }; timestamp = 1 report type = class

Why is timestamp's value 1 and not 2014-09-08:14:00T-004?

Neil Watson
watson-wilson.ca

Replies are listed 'Best First'.
Re: Help with getopt::long and GetOptionsFromArray
by Corion (Patriarch) on May 16, 2014 at 14:57 UTC

    The timestamp option seems to be a boolean option when you seem to intend to make it take a value.

    Did you mean to write

    GetOptionsFromArray ( \@args, \%query_params, 'timestamp:s' );

    ?

Re: Help with getopt::long and GetOptionsFromArray
by toolic (Bishop) on May 16, 2014 at 15:51 UTC
    Others have provided solutions to your problem. I think it is worth explicitly stating that your problem has nothing to do with GetOptionsFromArray. The same problem exists with GetOptions. If you really don't need GetOptionsFromArray, your code can be simplified:
    use strict; use warnings; use Data::Dumper; use Getopt::Long qw(GetOptions); use feature 'say'; my %query_params; print "perl args: ".Dumper( \@ARGV ); GetOptions ( \%query_params, 'timestamp=s' ); print "query_params: ".Dumper( \%query_params ); my $report_type = $ARGV[0]; say "timestamp = $query_params{timestamp}"; say "report type = $report_type"
Re: Help with getopt::long and GetOptionsFromArray
by Anonymous Monk on May 16, 2014 at 14:59 UTC

    From the docs: change 'timestamp' to 'timestamp=s'.