in reply to Re^2: Sub hash param by reference
in thread Sub hash param by reference

It's a whole lot easier and more subtle than you might expect. Perl actually passes parameters as aliases in @_ so we can:

use warnings; use strict; my %hash_rec = (id => "001"); doSub2($hash_rec{id2}); print "main: id2 = $hash_rec{id2}\n"; sub doSub2 { $_[0] = "Hello alias"; }

Prints:

main: id2 = Hello alias

We don't usually take advantage of that trick because without due care it's likely to lead to hard to maintain code.

Premature optimization is the root of all job security

Replies are listed 'Best First'.
Re^4: Sub hash param by reference
by hankcoder (Scribe) on Jul 08, 2016 at 04:54 UTC

    Hello GrandFather, thank you for your feedback and Wow, I never know param can do like that. I'm not quite understand what is $_[0] but I tested with it and it works well.

    sub doSub2 { # use name var instead of $_[0] so can easier to recall it my ($ref_value) = \$_[0]; $$ref_value = "Hello alias"; }

      Hello hankcoder,

      I'm not quite understand what is $_[0]

      The special variable @_1 is documented as follows:

      Within a subroutine the array @_ contains the parameters passed to that subroutine. Inside a subroutine, @_ is the default array for the array operators pop and shift.

      Now, in Perl2 you access the individual elements of array @my_array as $my_array[0], $my_array[1], $my_array[2], .... (Note that the first element has index zero.) In the same way, the array @_ (which is named “ _ ”) has elements $_[0], $_[1], $_[2], .... So $_[0] is the first parameter passed to the subroutine.

      1You can also call it @ARG if you use English; — see perlvar#General-Variables.
      2That is, Perl 5 and earlier. I believe Perl 6 uses a different syntax.

      Hope that helps,

      Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

        Thanks Athanasius for the clear explanation.