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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With