You could avoid some duplication by using the following syntax:

sub name { my $arg = ref $_[0] ? $_[0] : \do{my $anon = $_[0]}; # Do stuff. $$arg =~ s/^un//; return $$arg; }

or using an alias instead of a reference:

sub name { our $arg; local *arg = ref($_[0]) ? $_[0] : \do{my $anon = $_[0]}; # Do stuff. $arg =~ s/^un//; return $arg; }

Test code:

$i = $j = 'unchanged'; name(\$i); print("i:$i\n"); # i:changed $i = $j = 'unchanged'; $j = name($i); print("i:$i, j:$j\n"); # i:unchanged, j:changed $i = $j = 'unchanged'; $j = name(\$i); print("i:$i, j:$j\n"); # i:changed, j:changed

You could also check the calling context and avoid reference altogether:

sub name { our $arg; local *arg = defined wantarray ? \do{my $anon = $_[0]} : \$_[0]; # Do stuff. $arg =~ s/^un//; return $arg; }

but I'd avoid that since the it's not obvious what's going to happen when reading the call:

name($i); # In place $j = name($i); # Not in place sub test { name($_[0]) } # unknown!!! sub test { name($_[0]) } test($i); # In place sub test { name($_[0]) } $j = test($i); # Not in place

Update: Showed why wantarray is a bad idea instead of just saying it is.

Update: Fixed bug found by eff_i_g. That'll teach me to test without warnings.

Update: Oops, I forgot I should be able to read the argument, not just write to it. Fixed by changing \do{my ...} to \do{my ... = $_[0]}.


In reply to Re: Scalar and void subroutines by ikegami
in thread Scalar and void subroutines by eff_i_g

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.