in reply to Simple Pass By Reference

sub alter_var { my $var_in_sub = $_[0]; $var_in_sub =~ s/a/b/g; $_[0] = $var_in_sub; } # or sub alter_var { $_[0] =~ s/a/b/g; }

Replies are listed 'Best First'.
Re^2: Simple Pass By Reference
by tomazos (Deacon) on Jul 26, 2005 at 00:00 UTC
    That duplicates the content of $_[0] doesn't it? (Your first example)

    I want to pass it by reference, and give it a meaningful identifier in the context of the subroutine. (ie not have to use $_[0] throughout the subroutine.) (Your second example)

    -Andrew.


    Andrew Tomazos  |  andrew@tomazos.com  |  www.tomazos.com
      You can use a simple scalar reference, then.

      sub alter_var { my $scalar_ref = shift; $$scalar_ref =~ s/a/b/; } my $scalar = "foobarbaz"; alter_var( \$scalar );

      For more, see perlreftut.

      Also note that esskar's second example, which works on $_[0] directly, will alter the scalar passed into the parameter list. (In this case, $_[0] is an alias, not a reference, so there is no need to dereference anything.)

        I kind of wanted to use a local alias for $_[0], rather than have to use a reference that I have to remember to dereference everywhere.

        I guess I just want to say:

        alias $var_in_sub = $_[0];

        Just to give $_[0] a meaningful name in the context of the subrountine, such that $var_in_sub and $_[0] are the same thing. In the same way as $var_elsewhere and $_[0] are the same thing when calling alter_var($var_elsewhere).

        I guess this can't be done in Perl, without using references and dereferencing - which is fine. No big deal.

        -Andrew.


        Andrew Tomazos  |  andrew@tomazos.com  |  www.tomazos.com