in reply to Problem combining hashes

This all comes back to the error message:

Type of arg 1 to keys must be hash or array (not list) at - line 3, ne +ar "%Z)"

keys() really wants a hash as its single argument. Not a list. And %A, %Z is a list. Admittedly, it is a list of pairs that can again be interpreted as a hash, but keys() wants to have that hash.

Using +{ %A, %Z }->%* or %{{ %A, %Z }} constructs the list of pairs from the two hashes, wraps these in a hash reference and then dereferences that hash reference, giving the hash to keys(). This is why that one works.

Your other approaches fail because keys() only takes a single argument, and that argument must be a hash. Everything you try to pass to it is a list, because the comma operator "," creates a list or the assignments go through an intermediate list (and don't return the assigned hash).

If you are only interested in getting a unique list of keys, you could use List::Utils uniq, but that is not shorter than the two step approach, especially if you also later want to look at the combined values:

my @all_keys = uniq( keys(%A), keys(%Z) );

Replies are listed 'Best First'.
Re^2: Problem combining hashes
by jh (Beadle) on Mar 14, 2024 at 19:59 UTC
    I didn't use uniq() because I need unique keys, not values, so I'd have to call keys() twice and then use uniq() on the results. I figured this was simpler, LOL. I guess I was just surprised---args are so flexible in Perl I figured that keys() would be able to operator on an overlaid pair. But I guess it's no different than push() requiring the first arg be an array (not a list, not an arrayref, but an actual array).