in reply to VB-ish behaviour byVar or byRef of objects in Perl

The same applies to non-objects as well. Everything is passed by reference in Perl.

sub func { $_[0] = "bar"; } my $s = "foo"; func($s); print("$s\n"); # bar

Replies are listed 'Best First'.
Re^2: VB-ish behaviour byVar or byRef of objects in Perl
by webfiend (Vicar) on Dec 11, 2007 at 20:54 UTC
    Everything is passed by reference in Perl.

    I know it's true, but the common ways to handle subroutine arguments sort of make it untrue.

    sub fiddle { my ($arg) = @_; $arg = "waffle"; } sub faddle { my $arg = shift; $arg = "waffle"; } sub muddle { $_[0] = "waffle"; } my $value = "pancake"; print "$value\n"; # Prints "pancake" fiddle($value); print "$value\n"; # Prints "pancake" faddle($value); print "$value\n"; # Prints "pancake" muddle($value); print "$value\n"; # Prints "waffle"

    Shifting and slicing @_ into subroutine lexicals will make copies (which only matters for simple non-reference values). I know, I know. This is obvious stuff I'm talking about. But when somebody hears that everything is passed by reference in Perl, they also need to hear that it's a behavior that often gets bypassed in idiomatic code.

      Consider that it's because of the passed-by-aliasing behavior that those are the prevailing idoms . . . :)

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.