Re: type checks

[email protected] (sisyphus) Sat, 3 Jun 2023 23:11:14 +1000
Newsgroups perl.beginners
Message-ID <CADZSBj2pr2h3MyU7RQjy3CYLMNq1P1cQ_kTgi+EaPieas-ASnw@mail.gmail.com>
On Sat, Jun 3, 2023 at 10:16 PM sisyphus <[email protected]> wrote:

> [snip]
>
> It has since occurred to me that there's a simpler solution that meets the
> OP's spec - one that doesn't involve the creation of a specially designated
> module.
> Firstly, you just take the declaration of %flags as presented in
> Math::NumOnly:
> #########################
>   use B;
>   my %flags;
>   {
>     no strict 'refs';
>     for my $flag (qw(
>       SVf_IOK
>       SVf_NOK
>       SVf_POK
>               )) {
>       if (defined &{'B::'.$flag}) {
>        $flags{$flag} = &{'B::'.$flag};
>       }
>     }
>   }
> #########################
>
> However, you alter is_ok() to either return the numeric value of the
> scalar (if that scalar satisfies the OP's spec); otherwise the sub croaks:
>
> #########################
> sub is_ok {
>  die "Undefined value encountered" unless defined $_[0];
>   my $val = shift;
>   my $flags = flags($val);
>   die "Bad value encountered" if $flags =~ /SVf_POK/;
>   return $val
>      if $flags =~ /SVf_IOK|SVf_NOK/;
>   die "Bad value encountered";
> }
> #########################
>

I missed that sub flags() also needs to be available.


>
[snip]
>
> Similarly, instead of doing:
> $x += $y;
> you would do:
> is_ok($x) += is_ok($y);
>
>
Duh ... now that I test it, I realize  that doesn't quite work. - "Can't
modify non-lvalue subroutine call of &main::is_ok in multiplication ..."
Instead of:

is_ok($x) += is_ok($y);

you would need something like:

is_ok($x); # only if you need to check that $x is "ok"
$x += is_ok($y);

Cheers,
Rob