Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re^4: OO Perl Baby Steps

by tobyink (Canon)
on Jun 20, 2013 at 11:46 UTC ( [id://1039960]=note: print w/replies, xml ) Need Help??


in reply to Re^3: OO Perl Baby Steps
in thread OO Perl Baby Steps

Closures are totally workable as a basis for OO Perl...

#!/usr/bin/env perl use strict; use warnings; use Data::Dumper; { package Person; sub new { my $class = shift; my %store; bless sub { my ($action, $slot, $value) = @_; for ($action) { if (/fetch/) { return $store{$slot} } if (/store/) { return $store{$slot} = $value } if (/delete/) { return delete $store{$slot} } if (/exists/) { return exists $store{$slot} } } die; } => $class; } sub name { my $self = shift; @_ ? $self->(store => "name", @_) : $self->(fetch => "name") } sub age { my $self = shift; @_ ? $self->(store => "age", @_): $self->(fetch => "age") } } my $person = Person->new; $person->name("Bob"); $person->age("42"); print $person->name, " is ", $person->age, " years old.\n"; print Dumper($person);

However, they're slower than the more usual blessed hashref storage, because a method call will typically involve at least two sub calls.

For some reason I feel compelled to produce a MooseX module allowing you to use blessed coderefs for Moose objects like the example above.

package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1039960]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-04-25 19:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found