in reply to passing a hash ref in a sub
Simplifying a bit, references point to a memory location of a data structure. In your first piece of code, my $result_hr; will be undef because it isn't initialized. In your sub, you copy the elements of @_ into $raw_hr and $res_hr, so now $res_hr is just a copy of the original undef. In other words, it doesn't point anywhere! And $res_hr has no way to affect $result_hr. There is a hash being autovivified, but it is restricted to the scope of the sub.
When you write my $result_hr={};, now what is being passed into the sub is a reference that points to an anonymous hash. The reference still gets copied into $res_hr, but the result of that is just two references pointing at the same data structure. The hash isn't being autovivified in sub, instead the sub is modifying the anonymous hash pointed to by both $result_hr and $res_hr. When the sub returns, your main code still has access to the anonymous hash via the reference stored in $result_hr.
Note that there is a way to modify $result_hr from within the sub: use $_[1] directly, instead of $res_hr, because the elements of @_ are aliases to the original arguments. However, I wouldn't normally recommend this way of modifying arguments, because that they are in effect return values can be confusing to users of the API. It's more common to handle this via regular return values.
(Update before posting: I see davido has explained the same thing, with different wording - TIMTOWTDI :-) )
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: passing a hash ref in a sub
by davido (Cardinal) on Oct 31, 2018 at 15:21 UTC | |
by haukex (Archbishop) on Oct 31, 2018 at 15:34 UTC | |
by frazap (Monk) on Oct 31, 2018 at 15:43 UTC |