On May 20, Mark Martin said: >I'm moving database data from table to table and want to make sure I'm >getting only unique records.
This is similar to a topic that came up two days ago. >Only want unique $field1 and was looking at the cookbook code, but for that >I have to populate a hash and then re-inspect through before inserting >uniques, something like : > >%ucnt = (); >while (my @row = $sth->fetchrow) { > $field1 = $row[0]; > push(@list,$field1 ); > $ucnt{$_}++; > $field2 = $row[3]; >} > >@uniq = sort keys %ucnt; >foreach $item (@uniq) { >POPULATE TABLE............ >} > > >Surely I can avoid the "foreach" and inspect $field1 in the while loop for >uniqueness before pushing it to an array. You *can't* know something is unique until you've looked through all your data, but you CAN tell when something is NOT unique. You could do: my (%count, %unique); while (my @row = $sth->fetchrow) { my $field = $row[0]; if ($count{$field}++) { delete $unique{$field} } else { $unique{$field} = [ @row ] }; # or 1, or whatever you want } Here, every time a row is seen, its count is incremented. If the count (before incrementing) was true (that is, not 0), then we delete it from the unique hash. If the count was false (that is, 0), then we add it to the unique hash. This way you don't have to traverse over the %count hash for those elements whose value is 1, you have a hash of the elements in %count whose count is 1 already, the %unique hash. Does this solve your problem? -- Jeff "japhy" Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/ RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/ CPAN ID: PINYAN [Need a programmer? If you like my work, let me know.] <stu> what does y/// stand for? <tenderpuss> why, yansliterate of course. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>