I am facing difficulty understanding references in perl. Here is a short perl script to explain my problem [I ran this code using perl-5.8.3]:
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
my %a = ("a" => 1, "b" => 2);
my %b = ();
print Dumper(\%a, \%b);
foo(\%a, \%b);
print "+==After fn call==+\n";
print Dumper(\%a, \%b);
print "+-----------------------+\n";
bar(\%a, \%b);
print "+==After fn call==+\n";
print Dumper(\%a, \%b);
sub foo {
my($h1, $h2) = @_;
$h2 = $h1;
print Dumper($h2);
}
sub bar {
my($h1, $h2) = @_;
%{$h2} = %{$h1};
}
I guess in both subroutines, $h1 and $h2 are local vars. Still, bar() actually changes value of original %b, while foo() does not. Why is that?
this is the same exact behavior you would get if the values contained strings or any other simple value.
So basically, in the first example, you are just dealing with values, and normal value semantics apply. In the second case, you are dereferencing the values, which turns them back into their advanced types (in this case a HASH).