in reply to Re: Printing Categories from SQL search
in thread Printing Categories from SQL search

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

Replies are listed 'Best First'.
Re^3: Printing Categories from SQL search
by kcott (Archbishop) on Sep 27, 2018 at 08:14 UTC

    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

Re^3: Printing Categories from SQL search
by hippo (Archbishop) on Sep 27, 2018 at 08:07 UTC

    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.

Re^3: Printing Categories from SQL search
by wjw (Priest) on Sep 27, 2018 at 00:20 UTC

    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...