Kim Jonguk said:
Hi.
i'm reading a book about OOP with perl.
in constructor, for example
sub new
{
my ($class, %args) = @_;
...
bless { ... }, ref($class) || $class;
}
i'm wondering this. "ref($class) || $class".
i cannot understand this phrase.
plz, explain to me.
It's an idiom that makes the new() method usable as both an object
method and a class method. In a class-method call, (the normal way
to call new()), $class contains a string with a class name. In that
case, "ref( $class)" is "" (a false value), and the result of "ref( $class)
|| $class" is $class itself. If you call new() through an object,
$class will contain that object. Then, "ref( $class)" is the name
of the object's class. In both cases, bless() is called with a
class name, as it should be.
That said, in my opinion, using new() as an object method is not a
good idea. If "$object->new( ...)" creates an entirely independent
object, the presence of "$object" in the call is confusing, since it has
no consequences. If "$object->new( ...)" creates a clone of object,
then call the method "clone" or "copy", but not "new".
So, while the construct works and gives the new() method a spurious
universality, I'd just replace ""ref($class) || $class" with "$class".
Anno