in reply to unique elements in a Hash of Arrays?

Actually, this:

$unique_ids = scalar(grep {defined $_} @normal_array);

will not find the number of unique IDs in @normal_array, it'll simply count how many elements of @normal_array are defined. I recommend using the uniq function from List::MoreUtils.

Applying it to a hash of arrays is straightforward: just iterate through the keys, and apply it to each element of your hash (i.e., each array). Using your example:

foreach (sort keys %HoA) { say "$_: ", join ",", uniq @{ $HoA{$_} }; }

Output:

flintstones: fred,barney,nick,john jetsons: george,jane,elroy,mike,elias simpsons: homer,marge,bart,jack

If you can't or don't want to use this module, the Perl Cookbook has several solutions (Recipe 4.6, p. 102).

Replies are listed 'Best First'.
Re^2: unique elements in a Hash of Arrays?
by AnomalousMonk (Archbishop) on Jul 13, 2014 at 19:48 UTC
    I recommend using the uniq function from List::MoreUtils. ... If you can't or don't want to use this module ...

    Anonymonk: ... just take a look at the code in it to see how it works; i.e., Steal This Code!

Re^2: unique elements in a Hash of Arrays?
by Anonymous Monk on Jul 13, 2014 at 22:32 UTC
    Great thanks,
    can you also tell me how I can count the unique elements per key of the Hash of Arrays?

      Sure. uniq returns a list of unique elements, and lists evaluate to their number of elements in scalar context, so if you replace the line inside the foreach with e.g. this:

      say "$_: ", scalar uniq @{ $HoA{$_} };

      Then you'll get the number of unique items. (You could equally well assign to a variable for further processing, of course, and if you assign to a scalar, the explicit scalar won't be necessary, though it also won't hurt and may serve to make it a bit clearer what's going on.)

        Thank you SO much :)