Arsenii
Arsenii

Reputation: 774

HASH element from an object's return in a single string

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!

Upvotes: 3

Views: 381

Answers (2)

ikegami
ikegami

Reputation: 385565

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}

Upvotes: 6

ysth
ysth

Reputation: 98388

If a 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 with:

print +{ $m->getHash() }->{needed_element_key};

(The leading + is needed to prevent perl from thinking the { is a block returning a filehandle to print to.)

But you are better off just returning a hash reference.

Upvotes: 5

Related Questions