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.
|
|---|