Front page | perl.beginners |
Postings from June 2023
Re: type checks
Thread Previous
|
Thread Next
From:
sisyphus
Date:
June 2, 2023 11:49
Subject:
Re: type checks
Message ID:
CADZSBj1AMeuYM9Mrdkxwgg4KGxonQwMA4kmkhv4uFp-PEM1Xxw@mail.gmail.com
On Fri, Jun 2, 2023 at 5:56 PM <wesley@mxcloud.app> wrote:
> Hello,
>
> I am not sure, is there any external module to check types in such
> mathematical calculation?
>
> $ perl -le 'print ("3" + undef)'
> 3
> $ perl -le 'print ("3" + 4)'
> 7
>
> I hope the program will throw errors when the above happens.
>
Throwing an error would be quite contrary to the way perl has always
treated strings (and undef) in numeric context.
The details of obtaining the behaviour you want are, I think, beyond the
scope of this "beginners" list.
I would suggest going to
https://www.perlmonks.org/?node=Seekers%20of%20Perl%20Wisdom, scrolling
down to the bottom of the page and asking your question there. (Better
still, create a perlmonks account before posting ... though that is not
necessary.)
The difference (as perl sees it) between "3" and undef, can be demonstrated
as follows:
D:\>perl -MDevel::Peek -le "Dump '3';"
SV = PV(0x1babfc2b038) at 0x1babfc66488
REFCNT = 1
FLAGS = (POK,IsCOW,READONLY,PROTECT,pPOK)
PV = 0x1babfc96ee8 "3"\0
CUR = 1
LEN = 10
COW_REFCNT = 0
Note that the FLAGS don't mention IOK (signifying an integer) or NOK
(signifying a floating point number), but the POK flag is specified because
the argument given to Devel::Peek::Dump is a string.
Because you use the '+' operator with the string, the string is evaluated
in numeric context - and, in numeric context, the string "3" evaluates to
the integer value 3.
Therefore "3"+4 is evaluated as 7.
D:\>perl -MDevel::Peek -le "Dump undef;"
SV = NULL(0x0) at 0x24604cd7128
REFCNT = 2147483641
FLAGS = (READONLY,PROTECT)
In this instance neither the IOK nor NOK nor POK flag is set because undef
is neither an integer nor a float nor a string.
Because you use the '+' operator with undef, undef is evaluated in numeric
context - and, in numeric context, undef evaluates to 0.
Therefore undef+"3" (and also undef+3) will be evaluated to 3
The behaviour you seek is attainable - but, like I said, beyond the scope
of a beginners list.
The behaviour you seek is also rather unusual. In my 25 years with perl, I
don't recall ever seeing such a request.
Is there some particular reason that you want this behaviour ? (BTW, IMO
you don't need to have any such reason.)
Cheers,
Rob
Thread Previous
|
Thread Next