in reply to Re^2: How do I determine with a regular expression whether a scalar is a number/whole/integer/float?
in thread [SOLVED] How do I determine with a regular expression whether a scalar is a number/whole/integer/float?
But my goal is that I want with the use of a regular expression to determine what "category" is e.g. (integer, decimal, float).
This is the reason that I define my array my @numbers = (1, -1, 123.1, 0.1); without the qw so the values will not be strings but numbers.
What does a regular expression match against? Yup, a string.
So, no matter how you initialize your array, for the purpose of comparison against a pattern, its elements are converted into strings.
All conversions from string to number, from number to string, from integer to float and so on are done under the hood by perl, if necessary.
Read perldata. - A scalar value (SV) has various slots: IV (integer), PV (string pointer), NV (numeric value). The currently active slot is determined by the FLAGS field of the scalar:
use Devel::Peek; $c = 1; Dump $c; $c = "2"; Dump $c; $c = 3.141592653; Dump $c; __END__ SV = PVNV(0x176e4d0) at 0x1776f20 REFCNT = 1 FLAGS = (IOK,pIOK) IV = 1 NV = 1.23456789 PV = 0 SV = PVNV(0x176e4d0) at 0x1776f20 REFCNT = 1 FLAGS = (POK,pPOK) IV = 1 NV = 1.23456789 PV = 0x17a7900 "2"\0 CUR = 1 LEN = 16 SV = PVNV(0x176e4d0) at 0x1776f20 REFCNT = 1 FLAGS = (NOK,pNOK) IV = 1 NV = 3.141592653 PV = 0x17a7900 "2"\0 CUR = 1 LEN = 16
Note that after assigning $c the (shortened ;-) value of PI, the other slots - IV, PV - retain their previous values, but the FLAGS field now refers to NV: (NOK,pNOK).
Incrementing the string " 2 ", which to perl looks like a number, results in the allocation of a integer slot which holds the value 3 - and adding 0.141592653 results in the allocation of a NV slot:
use Devel::Peek; $c = " 2 "; Dump $c; $c++; Dump $c; $c+= 0.141592653; Dump $c; __END__ SV = PV(0x13f85f0) at 0x17c2de8 REFCNT = 1 FLAGS = (POK,pPOK) PV = 0x17e5820 " 2 "\0 CUR = 3 LEN = 16 SV = PVIV(0x1171478) at 0x17c2de8 REFCNT = 1 FLAGS = (IOK,pIOK) IV = 3 PV = 0x17e5820 " 2 "\0 CUR = 3 LEN = 16 SV = PVNV(0x17ba4d0) at 0x17c2de8 REFCNT = 1 FLAGS = (NOK,pNOK) IV = 3 NV = 3.141592653 PV = 0x17e5820 " 2 "\0 CUR = 3 LEN = 16
|
|---|