Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if coercion would be successful?

Tags:

raku

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.

like image 356
rogergl Avatar asked Nov 22 '25 12:11

rogergl


2 Answers

+'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
}
like image 157
Brad Gilbert Avatar answered Nov 24 '25 17:11

Brad Gilbert


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.

like image 44
Christoph Avatar answered Nov 24 '25 17:11

Christoph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!