There are a number of modules for converting hashes to blessed hashrefs with accessors for the elements within, f.e.
Data::AsObject and
Hash::AutoHash. In this code I imagined you'd be using an %employees hash rather than an array, and keyed it on some imaginary employee id. I then subclassed Data::AsObject::Hash to add a
new method to take a reference to the employees hash and create the accessors (through the
dao function) automatically.
I was able to add custom methods to my EmployeeData class which can work on $self as either a subclass of Data::AsObject::Hash or as a hashref (or hash, through dereferencing) and you can continue to use the %employees hash as before.
If you wished to use an array, then
dao would need to be given a hashref with one key and a reference to the array as the value, e.g.
dao { data => \@employees }.
Of course, you could just as easily have created a completely new class, which just blessed
\@employees (or
\%employees) into
$class and just used it as a means to add methods.
If you keep both %employees and $employees in the same scope it would provide a (really ugly) way of keeping the original array|hash and its blessed reference and using, f.e., both
push @employees, { name => 'Foo Bar' }; and
$employees->method_call; in the same code, though hopefully at some point you'd switch over to just the object/reference.
I don't this is some 'problem' which requires the use of slow modules like
autobox or some wholesale re-invention of Perl symbology. Just some reasonable amount of pre-planning and willingness to make reasonable, incremental changes in existing code.
use strict;
use warnings;
{
package EmployeeData;
use Data::AsObject;
use base 'Data::AsObject::Hash';
sub new {
my $class = shift;
my ($data) = @_;
my $obj = Data::AsObject::dao ( $data );
bless $obj, $class;
}
sub foo {
my $self = shift;
my ($eidx) = @_;
print STDERR $self->{$eidx}{age} . "\n";
}
}
my %employees = (
JS0114 =>
{ name => 'Joe Soap',
age => 56,
},
JS1282 =>
{ name => 'Joan Smith',
age => 28,
},
);
my $employees = EmployeeData->new(\%employees);
bless $employees, 'EmployeeData';
print $employees{JS0114}{age} . "\n";
$employees->foo('JS1282');
print $employees->JS0114->age . "\n";