For the following multi sub script:
multi sub Screen_get_valid_string($prompt, $accept_empty_string, $max_length = 999) { return "abc" }
multi sub Screen_get_valid_string($prompt, $max_length = 999) { return "def" }
my $return = Screen_get_valid_string("enter value for string => ", True);
say 'return is ', $return;
I receive the following error:
Ambiguous call to 'Screen_get_valid_string';
these signatures all match:
:($prompt, $accept_empty_string, $max_length = 999)
:($prompt, $max_length = 999)
The only way I found to have the right multi sub called was to use named parameters:
multi sub Screen_get_valid_string(:$prompt, :$accept_empty_string, :$max_length = 999) { return "abc" }
multi sub Screen_get_valid_string(:$prompt, :$max_length = 999) { return "def" }
my $return = Screen_get_valid_string(prompt => "enter value for string => ", accept_empty_string => True);
say 'return is ', $return;
The result is :
return is abc
Thank you
p.s. worked in Perl5; new to Perl6
The error you are getting is because you have the default value set. As such the parser doesn't know if you're asking for
$prompt = "enter value for string => "
$accept_empty_string = True
$max_length = 999
Or
$prompt = "enter value for string => "
$max_length = True
With no type hints there's no was to tell from just the positional which of the two options is correct. Adding types would help (as suggested by JJ Merelo). You can also mix and match positional and named arguments which may help in this situation :
sub Screen_get_valid_string( $prompt,
:$max_length = 999,
:$accept_empty_string = False )
In this situation you don't need a multi. $prompt
is always required and the other two are flags with default values.
I gave a talk covering the various options for signatures at LPM recently it might be helpful.
https://www.youtube.com/watch?v=obYlOurt-44
Of course you can go the whole hog with :
sub Screen_get_valid_string( Str() $prompt,
Int :$max_length = 999,
Bool :$accept_empty_string = False )
Note the Str()
accepts anything that will coerce to a Str.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With