in reply to Re: Mixed lvalue/rvalue sub function
in thread Mixed lvalue/rvalue sub function

Hi, I realize that the lvalue syntax looks a little weird, maybe I should kick it out and just have:
$obj->header('test'); # Get header 'test' $obj->header('test','new value'); # set header test $obj->header; # Get all headers as hash
You C++-ish suggestion:
my $hdr_slot = $self->header ('test'); $hdr_slot = "new value"; # Set print "New header: $hdr_slot\n"; # Get
doesn't work in Perl because there all objects are references (to talk C++: from type *myclass not myclass). So assigning to $hdr_slot would make this variable a string with the value "new value" and would remove the reference to the object. Overloading the '=' operator only is used for generating temp copies for operators like '+=', so far I know.

The only way to do this is to tie a class to $hdr_slot. Then you can define a STORE method which gets called at every '='. See 'perldoc perltie' for more.

I read all this in the book 'Object Oriented Perl' just two weeks ago.

Replies are listed 'Best First'.
Re^3: Mixed lvalue/rvalue sub function
by elmex (Friar) on Apr 18, 2008 at 13:44 UTC

    Ah, yes, you are of course completely right, I guess I did too much C++ recently :)

    Alternatively you could return a reference to the header, of course. But it would look kinda more ugly than the simple optional argument solution:

    my $slot = $self->header ('test'); $$slot = "New value"; print "Value for header: $$slot"; # or even $slot, if you overload the + stringification
      If you like to start using lvalue function, you should know that they are still marked as experimental (at least in Perl 5.8).

      perlsub says:

      WARNING: Lvalue subroutines are still experimental and the implementation may change in future versions of Perl.