Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Class::Struct question

by ikegami (Patriarch)
on Sep 14, 2004 at 18:17 UTC ( [id://390933]=note: print w/replies, xml ) Need Help??


in reply to Class::Struct question

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://390933]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-19 12:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found