Another issue has just come to mind. With the object attributes being keyed on "$self", which includes the name of the class, you can no longer bless an object into a sibling class to implement state transitions.
Again, I guess some people would consider this a feature. I quite like the technique myself :-)
To overcome you'll need to strip out the class name. Assuming nobody changes the output format of references in later perl versions something like this should work.
package Foo;
use strict;
use warnings;
use overload;
my %foo = ();
my %self = (); # we access self enough for it to be worth caching
sub self {
my $self = overload::StrVal shift;
return $self{$self} if exists $self{$self};
$self{$self} = substr($self, index($self, '=')+1);
};
sub new {
my $class = shift;
bless [], $class;
};
sub foo {
my $self = shift->self;
$foo{$self} = @_ if @_;
$foo{$self};
};
sub DESTROY {
my $self = shift->self;
delete $foo{$self};
undef %self;
};
Also, there is another advantage to Abigail-II's method. Storing the attributes in separate hashes should less expensive in memory - buckets cost less than hashes. Might make a difference if you're creating lots of objects.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|