Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

I have been learning Perl for a bit now and found it very different from other OOP languages I know. I tried to translate a C# code which goes like:

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

and a method (pseudocode) :

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

how do I write this in perl without a GetType function or is there one?

like image 537
PerlNewbie Avatar asked Jan 18 '11 20:01

PerlNewbie


2 Answers

In a lot of Perl code, the ref operator is what you want if you're seeking the exact name of the class of the object. Since it's undefined if the value is not a reference, you need to check the value before using string comparisons.

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

It's more likely that you want something like C#'s is operator. That would be the isa method of UNIVERSAL which is inherited by all objects. An example from the doc at 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") ) {
    ...
}
like image 96
psmay Avatar answered Oct 11 '22 14:10

psmay


ref should be what you need.

like image 43
hometoast Avatar answered Oct 11 '22 14:10

hometoast