1

I'm trying to grab a 3D vector as a single command line input argument using Perl (v5.14.2).

After going through the Getopt::Long documentation, I decided to start with this:

use Getopt::Long;
my @boxSize = (0, 0, 0);

GetOptions('box:f{3}' => \@boxSize);

print "Box size: $boxSize[0], $boxSize[1], $boxSize[2]\n";

Running this script with the arguments -box 1.0 2.0 3.0 yields:

Box size: 0 0 0

Now, if I leave @boxSize uninitialized:

use Getopt::Long;
my @boxSize; #= (0, 0, 0);

GetOptions('box:f{3}' => \@boxSize);

print "Box size: $boxSize[0], $boxSize[1], $boxSize[2]\n";

The same script now returns:

Box size: 1.0 2.0 3.0

Can anyone tell me what I'm doing wrong?

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
vishnusr
  • 13
  • 3
  • Welcome to SO! We usually don't add a thanks statement to keep things uncluttered. To thank people that help you be sure to upvote good answers and accept the best one. Thats all the thanks we need :-). Good first question btw. – Joel Berger Feb 26 '13 at 23:08

1 Answers1

3

I was about to say that you found a bug, and then I checked something: it turns out that when used this way, the values are appended. You are ending up with 6 values in @boxSize.

#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long;
my @boxSize = (0, 0, 0);

GetOptions('box:f{3}' => \@boxSize);

print "Box size: @boxSize\n";

The feature you are using is marked as experimental

Warning: What follows is an experimental feature.

but perhaps this should still be considered a bug considering that you specify three values.

In the meantime, as simple workaround would be to check if values were added and if not use your defaults.

#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long;
my @boxSize;

GetOptions('box:f{3}' => \@boxSize);
@boxSize = (0, 0, 0) unless @boxSize;

print "Box size: @boxSize\n";
Joel Berger
  • 20,180
  • 5
  • 49
  • 104