pistacchio
pistacchio

Reputation: 58923

Perl6 optional function flags

How can I implement functions that take an optional flag in Perl6? For example, say that I want to invoke my function like this:

format 'a b c';

or like this:

format :pretty 'a b c';

How can I do this? Thanks

Upvotes: 6

Views: 144

Answers (2)

user5854207
user5854207

Reputation:

If you really want that odd syntax, you can use an operator and some subsignature magic. The Bool method is optional and the class Pretty can be empty. It's just there to provide something for the MMD-dispatcher to hold onto.

class Pretty { method Bool {True} };
sub prefix:<:pretty>(|c){ Pretty.new, c };
multi sub format((Pretty:D $pretty, |a)){ dd $pretty.Bool, a };
multi sub format(|c){ dd c };
format :pretty 'a b c'; format 'a b c';
# OUTPUT«Bool::True␤\(\("a b c"))␤\("a b c")␤»

Upvotes: 3

Christoph
Christoph

Reputation: 169723

It's just a named argument, in case of flags a boolean one. This all works out because :pretty is syntactic sugar for the pair :pretty(True) aka pretty => True.

You can either use the boolean value

sub format($arg, Bool :$pretty = False) {
    if $pretty { ... }
    else { ... }
}

or use its presence for multi-dispatch

multi format($arg) { ... }
multi format($arg, Bool :$pretty!) { ... }

In the first example, we provided a default value (which isn't really necessary as the undefined value boolifies to False, but it's arguably the 'right thing to do' semantically), in the second one we made it a required parameter by adding the !.

Also note that named arguments still have to be separated by commas, ie you'd use it as

format :pretty, 'a b c';

Upvotes: 11

Related Questions