Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Simple Pass By Reference

by esskar (Deacon)
on Jul 25, 2005 at 23:54 UTC ( #478022=note: print w/replies, xml ) Need Help??

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 Tomazos  |  |
      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 Tomazos  |  |

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://478022]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2023-02-05 21:04 GMT
Find Nodes?
    Voting Booth?
    I prefer not to run the latest version of Perl because:

    Results (33 votes). Check out past polls.