Is there any function in Perl similar to GetType () in C #?

I studied Perl a bit and found that it is very different from other OOP languages ​​that I know. I tried to translate C # code that looks like this:

class Car{}, class CarList{}, class Program{}

and method (pseudo code):

if (var.GetType() == Car)
{
}
else if (var.GetType == CarList) 
{
}

how can i write this in perl without gettype function or is there one?

+5
source share
2 answers

In a lot of Perl code, a statement refis what you want if you are looking for the exact class name of an object. Since undefined, if the value is not a reference, you need to check the value before using string comparison.

if(ref $var) {
    if(ref($var) eq 'Car') {
        # ...
    } elsif(ref($var) eq 'CarList') {
        # ...
    }
}

, - # is. isa UNIVERSAL, . http://perldoc.perl.org/UNIVERSAL.html:

use Scalar::Util 'blessed';

# Tests first whether $obj is a class instance and second whether it is an
# instance of a subclass of Some::Class
if ( blessed($obj) && $obj->isa("Some::Class") ) {
    ...
}
+11

ref , .

+3

All Articles