HASH element from object is returned in one line
I have a Module.pm module with a function getHash()
that returns, you guessed it, a data hash)). We all know very well how to get the elemental form of this hash using the standard model:
use Module;
my $m = new Module;
my %hash = $m->getHash();
print $hash{needed_element's_key};
everything is good. But what if you need to write the last two lines on the same line WITHOUT initializing a new HASH (and taking up memory for the whole hash using only one element)?
Is it possible one way or another? For example, of $m->getHash()->{needed_element's_key};
course this example does not work. Any suggestions? Thank!
source to share
Cannot return hash. Subs can only return a list of scalars. You assign this list of scalars to existing hashes my %hash
and get an element of that hash.
You can hide the fact that you are creating a new hash using an anonymous hash:
my $val = { $m->getKeyValPairs() }->{$key};
Alternatively, a custom filter might 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 return a method instead of a hash. Then you don't have to do the wasteful activity of generating a hash. You just use the following:
$m->getHashRef()->{$key}
source to share
If sub does return %hash
, it actually returns a list of keys and values (alternating). You can put it back in a hash and get a specific key:
print +{ $m->getHash() }->{needed_element_key};
(The presenter is +
needed to prevent perl from thinking that {
is a block returning a file descriptor to print.)
But you better just return the hash link.
source to share