in reply to Problem combining hashes

One expression, no lingering temp vars. But you're really trying to oversimplify.

my @all_keys = do { my %c = ( %A, %Z ); keys %c };

The keys function wants a single argument that's a just literal hash or array variable of some form (e.g. either a literal %foo or a postderef $bar->%*). It used to at one point be valid to give a scalar to keys and it would (I believe; not 100%) automagically deref. My guess when you tried to give it multiple items keys( %A, %Z ) it's parsing out as list context and you're actually passing it a list of the two hashes' contents unrolled which is why it's triggering the experimental scalar error and the error that you've given it more than one argument.

Edit: Also you might want to take into account the sizes of the hashes involved. It may be much less data copying to iterate over the keys of each candidate hash separately and create a hash from those then take keys of that instead so you're not copying all the values around as well. Which is what the aforementioned uniq is pretty much doing under the hood already (although that's going to build a temporary list of the all the keys to pass as args instead of just iterating over them).

And another thing: If you do make the big überhash be aware that the value is going to correspond to the last key seen from the last hash containing it which you use (e.g. %c = ( %A, %B ) if both have a key "a" the value in $c{a} will have what is in $B{a}).

The cake is a lie.
The cake is a lie.
The cake is a lie.

Replies are listed 'Best First'.
Re^2: Problem combining hashes
by jh (Beadle) on Mar 14, 2024 at 20:06 UTC

    I guess it's one expression but it has a block and a semicolon in it so... (lol)

    I think you are right. When I tried to do keys(%A, %Z) it failed its arg magic and it was as if I had called keys("a", 1, "b", 2, "c", 3, "z", 9, "y", 8, "x", 7). It looked at its "one argument" ("a") and threw the "no scalars" error. I wouldn't call it a "bug" but it's a pretty misleading/confusing error message.

    I'm not worried about the sizes. In general, an excellent piece of advice, but in this case there will be literally twos of keys in each hash. I just wanted the union quick and easy.

    To your last point, sure, I use hash overlays on purpose all the time. In this case I only care about the keys, though.