Given
my $t=+"aaa";
is it possible tho check if the coercion will succeed (I know that it doesn't here) before using $t ?
BTW: What I really want to do is check if a string is a valid Integer. I know that I can use a regex for that purpose, but I suppose that there is a simpler solution.
+'aaa' results in a Failure which is a kind of Nil which is a bit like an undefined value.
Which means you can use anything that works with them.
my $t = +$s with +$s; # $t remains undefined
my $t = +$s // 0; # $t === 0
my $t = (+$s).defined ?? +$s !! 0;
Since what you want to do is check if it is an Int
my $t = +$s ~~ Int ?? +$s !! 0; # Failures aren't a type of Int
my $t = 0;
with +$s {
when Int { $t = $_ }
default { ... } # +$s is defined
} else {
... # optional else clause
}
Yet another version:
my $t = +"aaa" orelse note "could not coerce to numeric type";
say $t.^name; # Failure
orelse is the low-precedence version of //. In this version, the assignment to $t still happens, but the check for definedness handles the failure, ie it won't blow up and raise an error.
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