As a demo, I re-wrote your a1 sub and added an a2 sub.
Rather than assigning the hash reference in the subroutine to the "global" variable, I would recommend returning the hash reference from the sub as shown in recoded sub a1.
Like in C, it is possible to pass a "pointer", the hash reference to a sub as shown in sub a2. The memory previously used by sub a1 is "re-used", same struct is modified. If "my $href" goes out of lexical scope, its memory will be recovered and reused by Perl.
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; # a cool core module # that dumps any structure my $href = a1(); #hash reference returned from sub print "v1=$href->{'v1'}\n"; #dot operator not needed print Dumper $href; a2($href); print Dumper $href; exit(0); sub a1 { my %hash; $hash{v1} = 10; $hash{v2} = 20; return \%hash; # %hash memory will "live" due to # reference counting } sub a2 { my ($href) = @_; $href -> {v1} = 30; #quotes are ok but not needed $href -> {'v2'} = 40; return; } __END__ v1=10 $VAR1 = { 'v2' => 20, 'v1' => 10 }; $VAR1 = { 'v2' => 40, 'v1' => 30 };
In reply to Re: Do subroutine variables get destroyed?
by Marshall
in thread Do subroutine variables get destroyed?
by bt101
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |