in reply to Have hash of arrays. Want to test if variable is a member of any of the arrays

Usually, the things that are stored in arrays and hashes and such are references, and, if this be so, remember that there can be any number of references to the same thing.   If you frequently need to refer to things by a particular key, consider building a separate hash, whose members are (say ...) an arrayref containing references to these same things.   The hashref, in effect, becomes an index.   Perl’s “auto-vivification” features make this very easy.

Let’s say for the sake of example that the items being stored are individual hashrefs which contain, among other things, a field named key.   You could build an index of those items with something like this:

push @($index->{$item->{'key'}}), $item;

Notice how this statement, in a single statement, “simply refers to” an item in $index, referring to $index as a hashref as though Perl already knew that it was, and referring to the item as though it already existed, and referring to the hash-element thus identified, as an arrayref.   Automagically, Perl simply causes all of this to occur on-the-fly.   If $index is not yet defined, it automagically becomes a hashref.   If it does not yet have the prescribed key in it, the key magically appears.   And, since the element is being referred-to as an arrayref, that is what it automagically becomes.   And $item, which we have already said is a hashref, gets pushed onto it.

It is perfectly all right to have several different references to the same thing.   If you need for $item to also appear in other arrays as you did in the original code, you can put it there too.   But you don’t have to search for it.   The $index hash will contain a key for any key that exists, and it will point to an arrayref in which references ... functionally identical to any other reference to the same data-item which may exist elsewhere ... will be found to exist.   The data therefore, in effect, appears in two or more places at the same time.

Replies are listed 'Best First'.
Re^2: Have hash of arrays. Want to test if variable is a member of any of the arrays
by Anonymous Monk on Dec 13, 2014 at 15:35 UTC
    There is a syntax error in your code (parens should be curlies).