Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Tied hashes: multiple parameters to STORE()?

by vrk (Chaplain)
on Aug 22, 2008 at 13:53 UTC ( #706181=perlquestion: print w/replies, xml ) Need Help??
vrk has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,

suppose I wanted to create a tied hash class that supported storing multiple values per each key. Internally, this can be implemented by storing all values in an array (keeping in mind situations where the user may want to store array references as well). However, when inserting new values into the hash, is it possible to force Perl to evaluate $hash{$key} = @values; as $hash->STORE($key, @values);?

If not, then the only two ways to insert multiple values at a time are

  1. $hash{$key} = $_ for @values
  2. $hash{$key} = \@values

The first option is a bit clumsy, and the latter won't work if you want to be able to store array references in the hash.

My gut feeling is that there is no way around this, as the tied hash interface is defined as STORE(this, key, value), and besides that, the assignment is always parsed in scalar context for hashes. (Right?)

One way around it might be using overloading and lvalue subroutines (i.e. $hash{$key} would be overloaded syntax for $hash->store($key), where store() is an lvalue subroutine), but that doesn't seem elegant or, in fact, even a possible solution.

print "Just Another Perl Adept\n";

Replies are listed 'Best First'.
Re: Tied hashes: multiple parameters to STORE()?
by perrin (Chancellor) on Aug 22, 2008 at 18:00 UTC
    Frankly, this seems like a pointless exercise. The only reason to use tied variables for anything is to make code that doesn't know about the magic behind the TIE work. If your code has to know something about the tied variable and use different syntax, you might as well just use an object instead of a tied hash.
Re: Tied hashes: multiple parameters to STORE()?
by ikegami (Pope) on Aug 22, 2008 at 18:36 UTC

    I agree with perrin. The goal of tying is to provide the syntax of the variable to an object. It doesn't allow the creation of new syntaxes.

    Besides, the desired syntax ($hash{$key} = @array;) already has a very clear meaning: store the length of the array in the hash at the specified key.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://706181]
Approved by moritz
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (6)
As of 2018-05-21 21:13 GMT
Find Nodes?
    Voting Booth?