F
fishfry
Sometimes you have a class with a method that returns a list of
identical hashes, like this ...
sub listOfItems {
push @items, {_name => "larry", _value => 47};
push @items, {_name => "curly", _value => 93};
push @items, {_name => "moe", _value => 12};
return \@items;
}
The caller is going to iterate through the list and access the data like
this:
$items = listOfItems();
foreach $item (@$items) {
$name = $item->{_name};
}
For reasons of encapsulation and object-purity and so forth, you don't
want the caller to do that ... you'd rather have them write
$name = $item->name();
In order to do that, you'd have to make a separate package to define a
class for the name/value hash. But that's sort of an overkill ... not
every little hash deserves to be a class.
I'm wondering if there is some way to make the name/value hash a
mini-class somehow, so that you could define accessor methods, without
having to write a full-blown package that blesses the hash into a class.
I believe in Java this would be called an inner class. Is that right?
And on CPAN I've noticed a couple of contributions that say they
implement inner classes.
Is there a clever technique to do what I want? And/or is one of the
inner class CPAN packages appropriate?
identical hashes, like this ...
sub listOfItems {
push @items, {_name => "larry", _value => 47};
push @items, {_name => "curly", _value => 93};
push @items, {_name => "moe", _value => 12};
return \@items;
}
The caller is going to iterate through the list and access the data like
this:
$items = listOfItems();
foreach $item (@$items) {
$name = $item->{_name};
}
For reasons of encapsulation and object-purity and so forth, you don't
want the caller to do that ... you'd rather have them write
$name = $item->name();
In order to do that, you'd have to make a separate package to define a
class for the name/value hash. But that's sort of an overkill ... not
every little hash deserves to be a class.
I'm wondering if there is some way to make the name/value hash a
mini-class somehow, so that you could define accessor methods, without
having to write a full-blown package that blesses the hash into a class.
I believe in Java this would be called an inner class. Is that right?
And on CPAN I've noticed a couple of contributions that say they
implement inner classes.
Is there a clever technique to do what I want? And/or is one of the
inner class CPAN packages appropriate?