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?)
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;
}
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;
}
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;
}
A hash is a basic data type in Perl. It uses keys to access its contents. A hash ref is an abbreviation to a reference to a hash. References are scalars, that is simple values. It is a scalar value that contains essentially, a pointer to the actual hash itself.
$hash{key} is a single element within the hash. Therefore, \%hash is a reference to %hash , i.e., the whole hash, which appears to be what you intend to return in this case. \$hash{key} is a reference to a single element.
The Perl print hash can used $ symbol for a single hash key and its value. The Perl print hash can use the % symbol for multiple hash keys and their values.
The exists() function in Perl is used to check whether an element in an given array or hash exists or not. This function returns 1 if the desired element is present in the given array or hash else returns 0.
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.
Why not return both? Context is a very powerful feature in Perl to allow your functions to "do what you mean". Often the decision of which is a better return value depends on how the calling code plans to use the value, which is exactly why Perl has the builtin wantarray
.
sub build_hash {
my %hash;
@hash{@keys} = (1) x @keys;
wantarray ? %hash : \%hash
}
my %hash = build_hash; # list context, a list of (key => value) pairs
my $href = build_hash; # scalar context, a hash reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With