What is the Perl equivalent of the Python type () function

I can do it in Python:

>>> type(1)
<class 'int'>

What is the Perl equivalent?

+3
source share
5 answers

Perl does not make a hard distinction between strings and numbers like Python or Ruby do. In Perl, using operators determines how the variable will be interpreted.

In Python, when you write 1 + 2, Python checks the type of each argument, sees that these are numbers, and then does the add ( 3). If you write '1' + '2', it sees that both are strings, and performs concatenation ( '12'). And if you write 1 + '2', you will get a type error.

Perl, 1 + 2, + . ( , ), (3). '1' + '2', - 3.

, .: 1 . 2, '12', .

, Perl , ( ) . , , Scalar::Util looks_like_number, Perl .

Perl :

  • undefined (undef)
  • ( )

ref , .

ref(1)         --> ''  (a false value)
ref('string')  --> ''  (a false value)
ref([1, 2, 3]) --> 'ARRAY'
ref({a => 1})  --> 'HASH'
ref(\1)        --> 'SCALAR'
ref(\\1)       --> 'REF'
ref(sub {})    --> 'CODE'

perldoc -f ref

bless ed , . ref , .

{package My::Object;
    sub new {bless {}}
}

my $obj = My::Object->new;

ref($obj)  -->  'My::Object'
+9
+6

, _INTEGER.

, Scalar::Util::blessed - . , ref , . ( Perl.)


Perl TIMTOWTDI (YMMV) , , , , . .

+4

'isa', , ( , , ). 'ref' , , , .

AFAIK, , Perl, Python.

+3
source

If you want to check if something is integer, you can try the following:

use Scalar::Util;

if ( defined $value
  && !ref $value 
  && ref \$value eq 'SCALAR' 
  && Scalar::Util::looks_like_number($value)
  && $value =~ /^-?[0-9]+$/msx
) {
    printf '%s is an integer', $value;
}
+1
source

Source: https://habr.com/ru/post/1796027/


All Articles