in reply to Printing Categories from SQL search

One option in deduplication is usually a hash:

my %cats; while (my $pointer = $sth->fetchrow_hashref) { $cats{$pointer->{category}} = 1; } for my $category (keys %cats) { print "$category\n"; }

See also the FAQ How can I remove duplicate elements from a list or array?

Update: typo now fixed (line 3 was $cat{...}). Thanks wjw for spotting.

Replies are listed 'Best First'.
Re^2: Printing Categories from SQL search
by htmanning (Friar) on Sep 27, 2018 at 00:08 UTC
    Thanks so much. I wasn't able to get the above hash to work, but the following worked. Is there anything wrong with this?
    while ($pointer = $sth->fetchrow_hashref) { $category = $pointer->{'category'}; unless (!$category || $category ~~ @list) { print "<LI>$category\n"; } push (@list, "$category"); } #end while

      G'day htmanning,

      "Is there anything wrong with this?"

      The use of smart matching (~~) is experimental, so that's not good. It also looks like you're using (global) package variables: not good either - put use strict; at the start of your code and see what that tells you.

      I rather agree with ++afoken's comment about using the SQL to get rid of the duplicates; however, for cases where you don't have that option, the classic, general solution would be something like:

      my %seen; while (...) { next if $seen{$_}++; print; }

      You introduced @list which didn't exist in your OP. You already have the data that's in that array:

      keys %seen

      — Ken

      There was indeed a typo in my code above (now fixed) - sorry about that.

      The only problems with your presented solution are that you are using the smartmatch operator which is deprecated and also it's unlikely to be as fast. If you can't change the DB query to use DISTINCT as others have suggested, I'd still recommend the hash approach.

      If it works, generally there is nothing wrong with it. If you look closely you will see why the previous answer did not work (just a typo I think). Examine the 'cat(s)'...

      ...the majority is always wrong, and always the last to know about it...

      A solution is nothing more than a clearly stated problem...