Well, of course it is possible. The key module to use is overload. You can the overload the differnt reference access methods. Now, since bless needs a reference to something, I haven't been able to figure out how to overload all dereferencing operations at the same time. Anyway here is the code:
package Mutator;
use overload '%{}'=>\&as_hash,
'${}'=>\&as_scalar,
'@{}'=>\&as_array;
sub new{
my $class=shift;
my $scalar; #To get be able to create a scalar ref.
#This is where we store the real values. We use a closeure
#below, so %ref will be associated with our anon. sub.
#If you want to do some init of the variables, you can
#do it here.
my %ref=(hash=>{},
array=>[],
scalar=>\$scalar,
);
# Now this is the sub that returns the actual reference
# that we use. We call it in the overloaded methods.
my $sub=sub {
my $arg=shift;
return $ref{$arg};
};
#bless the anon. sub into this class
return bless $sub, $class;
}
#Get hash ref
sub as_hash{
my $s=shift;
return $s->("hash");
}
#Get scalar ref
sub as_scalar{
my $s=shift;
return $s->("scalar");
}
#get array ref
sub as_array{
my $s=shift;
return $s->("array");
}
1;
An questions?
GoldClaw
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.