Hi,
I have an OO method which should return/set a value stored in one hash of the object (not the blessed object hash). In order to have multiple ways to do it I'm using :lvalue to allow the assignment of a value to the method call, i.e.:
$obj->header('My Header', 'value'); # Set $obj->header('My Header') = 'value'; # Set if ($obj->header('My Header') eq 'value' ) { # Get ...
Know the overkill: When the method is called without an argument (except $self) it should return the internal header hash as ref, as rvalue would be enough.

I know the return statement must be omitted in order to make lvalue work. Because subs return then the return value of the last statement I thought I just put the two different return values at the end of a if () { } else { } statement. This returns an error message (Can't return a temporary from lvalue subroutine), so I put in a return statement for the hash ref.
Now it's working: lvalue for hash element, rvalue for whole hash. The code looks like this:

sub header : lvalue { my ( $self, $h, $value ) = @_; if ( @_ == 1 ) { return $self->{header}; } $self->{header}->{$h} = $value if defined $value; $self->{header}->{$h}; }
My question now: Is this clean enough or already a dirty trick or "black magic"? I would love to hear the opinion from a Perl guru with deeper insight in lvalue subs.

Thanks


In reply to Mixed lvalue/rvalue sub function by mscharrer

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.