Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my command line argument being interpreted as a Boolean (Perl 6)?

Given this program:

#!/bin/env perl6
sub MAIN ($filename='test.fq', :$seed=floor(now) )
{
    say "Seed is $seed";
}

When I run it without any command line arguments, it works fine. However, when I give it a command line argument for seed, it says that its value is True:

./seed.p6 --seed 1234
Seed is True

Why is the number 1234 being interpreted as a boolean?

like image 504
Christopher Bottoms Avatar asked Dec 24 '22 19:12

Christopher Bottoms


2 Answers

Perl 6's MAIN argument handling plays well with gradual typing. Arguments can, and should be typecast to reduce ambiguity and improve validation:

#!/bin/env perl6                                                                                                                                    
sub MAIN (Str $filename='test.fq', Int :$seed=floor(now))
{
    say "Seed is $seed.";
}

After typecasting seed to Int, this option must be given a numeric argument and no longer defaults to a Boolean:

perl6 ./seed.pl -seed 1234
Usage:
  ./seed.pl [--seed=<Int>] [<filename>] 


perl6 ./seed.pl -seed=abc
Usage:
  ./seed.pl [--seed=<Int>] [<filename>] 


perl6 ./seed.pl -seed=1234
Seed is 1234.
like image 102
dwarring Avatar answered May 10 '23 23:05

dwarring


You need to use an = sign between your option --seed and its value 1234:

./seed.p6 --seed=1234

Since you have a positional argument in your MAIN subroutine signature (i.e. $filename), the first argument not tied to an value with an = sign will be assigned to it.


Your original

./seed.p6 --seed 1234

was being interpreted as if 1234 were the filename (i.e. it was assigned to the variable $filename). Since a command line option without an argument is considered to be True, $seed was being assigned True in your original invocation of that script.

like image 26
Christopher Bottoms Avatar answered May 10 '23 23:05

Christopher Bottoms