Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle properties on a SCALAR based Perl class?

Tags:

class

perl

scalar

In Perl, it's easy to bless a hashref and use it to store and read properties:

package MyPackage;
use strict;
use warnings;

sub new {
    bless {}, __PACKAGE__;
}

sub SomeProperty {
    my $self = shift;
    if (@_) {
        return $self->{SomeProperty} = shift;
    }
    $self->{SomeProperty};
}

# Or even like this to be able to call $obj->OtherProperty = $x;

sub OtherProperty : lvalue {
    my $self = shift;
    $self->{OtherProperty};
}

But, I've seen some Classes (from different Perl modules) that, when dumped, show a simple scalar blessed:

$obj = bless( \$8756489, 'Some::Package' );

Yet, they have methods and properties. The methods I understand, any subroutine a package can call then will be called when asking a blessed $object->name. The part I'm not understanding is how they can store properties. Where are those properties being stored?

Several times they accept things like $obj->property = $x or $obj->property($x) and can be independent of other instances of the same Class. Where are those properties being stored?

I know that really depends on the underlying implementation of the Class, what it is doing or what it is interacting with, and that can actually answer the question several times (e.g. the object is just interfacing with another object or connection somewhere and only sending or quering values to it).

However, if there's a way for a scalar based object to store properties (like in a different concept or approach to class structure in Perl), I'd really like to know it.

Thanks in advance for any comments! :-)

like image 601
Francisco Zarabozo Avatar asked Aug 21 '13 19:08

Francisco Zarabozo


1 Answers

Well, one way is to use inside-out objects. Another is to use an XS-based class, where the scalar stores the address of a C/C++ structure in which the properties are stored (this is normally done only when the class's purpose is to interface with a C/C++ library).

You could also do something weird like index parts of the scalar using substr or pack, but I doubt anybody's done that except to prove it could be done.

like image 132
cjm Avatar answered Sep 27 '22 18:09

cjm