Skip to content

Commit 3e5dcec

Browse files
author
Tadeusz Sośnierz
committed
Allow optional named parameters in CommandLine.pm
Specified with foo=s? get the passed value if any, empty string otherwise. So --foo will set %options<foo> to '', --foo=bar will result in %options<foo> := 'bar'. In the first case, %options<foo> will still be false, but the existance of the argument can be checked with pir::exists()
1 parent 6fe5a07 commit 3e5dcec

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

src/HLL/CommandLine.pm

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,12 @@ class HLL::CommandLine::Parser {
178178

179179
method wants-value($x) {
180180
my $spec := %!options{$x};
181-
$spec eq 's';
181+
pir::substr($spec, 0, 1) eq 's';
182+
}
183+
184+
method optional-value($x) {
185+
my $spec := %!options{$x};
186+
$spec eq 's?';
182187
}
183188

184189
method parse(@args) {
@@ -226,9 +231,12 @@ class HLL::CommandLine::Parser {
226231
$value := pir::substr($opt, $idx + 1);
227232
$opt := pir::substr($opt, 0, $idx);
228233
$has-value := 1;
234+
} elsif self.optional-value($opt) {
235+
$value := '';
236+
$has-value := 1;
229237
}
230238
pir::die("Illegal option --$opt") unless pir::exists(%!options, $opt);
231-
pir::die("Option --$opt does not allow a value") if %!options{$opt} ne 's' && $has-value;
239+
pir::die("Option --$opt does not allow a value") if !self.wants-value($opt) && $has-value;
232240
if !$has-value && self.wants-value($opt) {
233241
$value := get-value("--$opt");
234242
}

0 commit comments

Comments
 (0)