开发者

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

This question already has answers here: How do I tell what type of value is in a Perl variable? (5 answers) Closed 9 years ago.

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.GetTy开发者_Go百科pe == CarList) 
{
}

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


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") ) {
    ...
}


ref should be what you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜