LinuxGuru-Wannabe
LinuxGuru-Wannabe

Reputation: 23

Simulate Python like “property” in Perl

I am fairly new to perl and I was wondering if there is a way to simulate python's property decorator in perl? After googling I have came across accessors and attributes but accessors are just providing getters/setters and I didn't find good documentation for attributes. All I want is to have a variable, which is when read a calls to getter method is invoked and the value comes from the getter method (I don't care about the setter in my scenario but will be nice to know if that could be simulated too).

Here is what property getter looks like in Python:

   >>> class PropertyDemo(object):
   ...     @property
   ...     def obj_property(self):
   ...             return "Property as read from getter"
   ... 
   >>> pd = PropertyDemo()
   >>> pd.obj_property()
   >>> pd.obj_property
   'Property as read from getter'

Here is my (failed) attempt to do something similar in Perl:

#!/usr/bin/perl
my $fp = FailedProperty->new;
print "Setting the proprty of fp object\n";
$fp->property("Don't Care");
print "Property read back is: $fp->{property}\n";
BEGIN {
    package FailedProperty;
    use base qw(Class::Accessor );
    use strict;
    use warnings;

    sub new {
        my $class = shift;
        my $self = {property => undef};
        bless $self, $class;
        return $self;
    }   

    FailedProperty->mk_accessors ("property" );
    sub property {
         my $self = shift;
         return "Here I need to call a method from another module";
    }   

    1;  
}
1;

Running this perl code does not set the key's value in the perl object and neither does it seem to call the right accessor:

perl /tmp/accessors.pl
Setting the proprty of fp object
Property read back is:

I was expecting that fp->{property} would give me "Here I need to call a method from another module" back.

Upvotes: 1

Views: 199

Answers (2)

clt60
clt60

Reputation: 63932

I'm not fully understand your question, but maybe the next covers it:

#!/usr/bin/env perl

use strict;
use warnings;

package Foo;
use Moose;
#the property is automagically the getter and setter
has 'property' => (is => 'rw', default => 'default value');

package main;
my $s = Foo->new();         #property set to its default
print $s->property, "\n";   #property as "getter"
$s->property("new value");  #property as "setter"
print $s->property, "\n";   #property as "getter"

prints

default value
new value

Upvotes: 0

Michael Carman
Michael Carman

Reputation: 30831

$fp->{property} is a hash lookup, not a method invocation. You're bypassing your OO interface and interacting directly with the object's implementation. To invoke your accessor, use $fp->property() instead.

I don't see why your using Class::Accessor and also defining the property method manually. Do one or the other, not both.

Upvotes: 3

Related Questions