On the plus side, it's possible, and you don't even need overloaded operators.
use strict;
use warnings;
package MyStruct;
sub new {
my $class = shift(@_);
return bless({@_}, $class);
}
sub Counter : lvalue {
my $self = shift(@_);
$self->{'Counter'} = $_[0] if (scalar(@_));
$self->{'Counter'}
}
package main;
{
my $x = MyStruct->new(Counter=>0); print($x->Counter, "\n"); # 0
$x->Counter($x->Counter + 1); print($x->Counter, "\n"); # 1
$x->Counter = $x->Counter + 1; print($x->Counter, "\n"); # 2
++($x->Counter); print($x->Counter, "\n"); # 3
++$x->Counter; print($x->Counter, "\n"); # 4
$x->Counter++; print($x->Counter, "\n"); # 5
$x->Counter += 1; print($x->Counter, "\n"); # 6
}
On the downside, you can't use Class::Struct with this method, or you have modify it slightly. I think the changes are limited to the following:
Change (untested)
$out .= " sub $name {$cmt\n my \$r = shift;\n";
to
$out .= " sub $name : lvalue {$cmt\n my \$r = shift;\n";
and scalar accessors will be returned by lvalue. Array accessors and hash accessors need a little more changes, because they use 'return' than that wipes the lvalue-ness.
-
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.
|