Why would I return a hash or a hash reference in Perl?
hash, perl, reference
Solution
I prefer returning a hash ref for two reasons. One, it uses a bit less memory since there's no copy. Two, it lets you do this if you just need one piece of the hash.
my $value = build_hash()->{$key};
Learn to love hash references, you're going to be seeing them a lot once you start using objects.
Problem
What is the most effective way of accomplishing the below? (I know they accomplish the same thing, but how would most people do this between the three, and why?) File a.pl ``` my %hash = build_hash(); # Do stuff with hash using $hash{$key} sub build_hash { # Build some hash my %hash = (); my @k = qw(hi bi no th xc ul 8e r); for ( @k ) { $hash{$k} = 1; } # Does this return a copy of the hash?? return %hash; } ``` File b.pl ``` my $hashref = build_hash(); # Do stuff with hash using $hashref->{$key} sub build_hash { # Build some hash my %hash = (); my @k = qw(hi bi no th xc ul 8e r); for ( @k ) { $hash{$k} = 1; } # Just return a reference (smaller than making a copy?) return \%hash; } ``` File c.pl ``` my %hash = %{build_hash()}; # Do stuff with hash using $hash{$key} # It is better, because now we don't have to dereference our hashref each time using ->? sub build_hash { # Build some hash my %hash = (); my @k = qw(hi bi no th xc ul 8e r); for ( @k ) { $hash{$k} = 1; } return \%hash; } ```