in reply to modify variable on pass by value

If you pass an lvalue to a subroutine, then assigning to the corresponding element of @_ will alter the lvalue, as in:
sub remove_caps { $_[0] =~ tr/A-Z//d; }
But now that you've asked for this, and I've answered it, let me give you some advice. Don't write subroutines like this. Perl works much better in a flow model, not a do-this-to-that model. For example, early versions of HTML::Entities::encode_entities worked that way, and after Gisle found enough places where it was a real bear to use, he changed it to be a return-value operator (with a backwards-compatibility mode).

So, save yourself the trouble. Use the return value. Don't alter the arguments.

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
(Ovid) RE(2): modify variable on pass by value
by Ovid (Cardinal) on Sep 11, 2000 at 20:28 UTC
    Perl works much better in a flow model, not a do-this-to-that model.
    merlyn, while I don't exactly consider myself a slouch as a programmer, I'm not sure what you mean by this. Are you saying it's more efficient to assign the value to something else as opposed to changing a variable in place? Or are you referring to a structured programming thing as opposed to an efficiency issue? Or rather, are you meaning something else entirely?

    Inquiring minds want to know...

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just go the the link and check out our stats.

      I'm not talking about efficiency. I'm talking about natural flow in programming. Every time I have to stop to use a foreach loop because a map wouldn't work, I have to create temporary variables, think of reasonable names for them, and then document them, and ensure their scope is large enough but not too large.

      Don't get me wrong. I'm not an FP fascist. But most of the time, temporary values forced on me by the syntax just seems awkward.

      Let's go back to this remove-cap function. In a return-value situation, I can use it like this:

      my @data = map { RemoveCaps $_ } @input;
      Whereas in a act-on-arguments mode, I've got to write this:
      my @data = map { my $x = $_; RemoveCaps $x; $x } @input;
      I can't use $_ directly, because it would attempt to alter @input (see the other thread on that {grin}). So now I have to invent a stand-in, just so I can act on it.

      Just one guy's opinion from someone who's been coding for 30+ years.

      -- Randal L. Schwartz, Perl hacker

        It seems that the author of the question wants symantics that are like chop. People know what chop is going to do to their variable. If the user is well aware of the way the subroutine will work, is it all that bad? Since you would have to do that with chop anyway?

        Just one guy making conversation with someone who's been coding for 30+ years (honest). {grin}

        --
        Casey