I have a module Module.pm with function getHash() which returns, as you guessed, a hash of data)). We all know well how to get an element form that hash, using a standard model:
use Module;
my $m = new Module;
my %hash = $m->getHash();
print $hash{needed_element's_key};
everything is ok. But what if you need to write two last strings in a single string WITHOUT initializing a new HASH (and occupying a memory for a whole hash, using just one element)?
Is it possible to do so somehow? Like, say, $m->getHash()->{needed_element's_key};
Of course, the given example does not work.
Any suggestions?
Thanks!
It's impossible to return a hash. Subs can only return a list of scalars. You are assigning that list of scalars to an existing hash my %hash and getting an element of that hash.
You could disguise the fact that you are creating a new hash by using an anonymous hash:
my $val = { $m->getKeyValPairs() }->{$key};
Alternatively, a custom filter could be more efficient:
sub find_val {
my $target_key = shift;
while (@_) {
my $key = shift;
my $val = shift;
return $val if $key eq $target_key;
}
return undef;
}
my $val = find_val $key, $m->getKeyValPairs();
But the best option would be to have the method return a reference to a hash instead. Then, you wouldn't have to perform the wasteful activity of creating a hash. You'd simply use the following:
$m->getHashRef()->{$key}
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