Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Tied hashes: multiple parameters to STORE()?

by w-ber (Hermit)
on Aug 22, 2008 at 13:53 UTC ( #706181=perlquestion: print w/ replies, xml ) Need Help??
w-ber 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";

Comment on Tied hashes: multiple parameters to STORE()?
Select or Download Code
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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://706181]
Approved by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (13)
As of 2014-07-10 22:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (217 votes), past polls