in reply to Sub hash param by reference

I've cleaned up the code a bit, and then made some fixes. you're trying to dereference things that aren't refs ;) Read the inline comments...

use warnings; use strict; my %hash_rec; $hash_rec{id} = "001"; doSub1(\%hash_rec); print "back main, id=$hash_rec{'id'}, id2=$hash_rec{'id2'}\n"; sub doSub1 { my ($hash_ref) = @_; print "inside doSub1, id=$hash_ref->{id}\n"; # you're not assigning a reference to $hash_ref->{id2}, # you're assigning a simple string $hash_ref->{id2} = "002"; # you're only sending a scalar string to doSub2()... # $hash_ref->{id2} eq "002" doSub2($hash_ref->{id2}); } sub doSub2 { # $id2_ref is NOT a reference... it's the value of # $hash_ref->{id2}, which is a scalar string only my ($id2_ref) = @_; print "inside doSub2, id2=$id2_ref\n"; # no need to deref this! }

Output:

inside doSub1, id=001 inside doSub2, id2=002 back main, id=001, id2=002

-> is the canonical dereference operator that you should be using, and don't put & at the beginning of sub calls. That's legacy perl 4 code, and isn't needed/shouldn't be used unless you know why you need them. Also, there's no need to define a main() sub. All portions of your program that are not wrapped in subs (or external modules, which you're not using here) already belong to "main".

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

    Hi Stevie, thanks for the feedback. Your code is good, However, on doSub2 is not what I am looking for. The value pass to doSub2 need to be in reference as the value may change inside that sub.

      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

        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"; }