检查强制是否成功?

Check if coercion would be successful?

给出

my $t=+"aaa";

是否可以在使用 $t 之前检查强制转换是否成功(我知道它不会成功)?

顺便说一句:我真正想做的是检查一个字符串是否是一个有效的整数。我知道我可以为此目的使用正则表达式,但我想有一个更简单的解决方案。

将它包裹在 try 块中以捕获异常。

my $t;
try {
  $t = +"aaa";
  CATCH { say "the coercion didn't work" when X::Str::Numeric; }
}

+'aaa' 导致失败,这是一种 Nil,有点像未定义的值。 这意味着您可以使用任何适用于它们的东西。

my $t = +$s with +$s; # $t remains undefined
my $t = +$s // 0; # $t === 0
my $t = (+$s).defined ?? +$s !! 0;

因为你想做的是检查它是否是一个 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
}

另一个版本:

my $t = +"aaa" orelse note "could not coerce to numeric type";
say $t.^name; # Failure

orelse// 的低优先级版本。在这个版本中,对 $t 的赋值仍然发生,但是对定义性的检查处理了失败,即它不会爆炸并引发错误。