Core module overload allows you to overload dereferencing. If you overload hash dereferencing only, you may have it. Something like this, perhaps:
{ package TwoFaceRefs; use overload '%{}' => \&getByKey; my %idx = qw(name 2); # And probably some more :-) sub getByKey { # Likely faster to return a tied hash, # but you get the idea ... my $obj = shift; return {map{ $_ => $obj->[$idx{$_}] } keys %idx}; } sub dsfmm { # Assuming we get an arrayref: my $obj = do_stuff_from_my_module(); bless $obj, "TwoFaceRefs"; return $obj; } } my $obj = TwoFaceRefs::dsfmm(); my $name = $obj->[2]; # # or # my $name = $obj->{name};
Update: Comment and (a little) whitespace added.
Update 2: Oh, unless we make getByKey return
a (properly) tied hash, assigning to the fields won't
work:
$obj->{name} = "Sidhekin";
The original problem merely stated to access
the fields, not setting them, but I just wanted to
make it clear that this is one problem overloading
(on its own) will not solve. (There is no problem
overloading and tying together cannot solve. Well,
okay. A few.)
The Sidhekin
In reply to Re: Scalar ref acting as simulatenous hash and array?
by Sidhekin
in thread Scalar ref acting as simulatenous hash and array?
by Masem
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |