in reply to Class::DBI 'distinct' records

I haven't used Class::DBI for a lot of projects, but I've been looking for such a method myself and haven't found one. Here's how I normally handle it, assuming username is a unique column that isn't the primary key:

my ($username) = My::DBI::Users->search( username => 'foo' ); # Could also do: my $username = (My::DBI::Users->search( username => 'foo' ))[0]; # Or maybe (haven't tried this one) my $username = My::DBI::Users->search( username => 'foo' ) ->next();

In the first example, search will generate a list, the first element of which we save to $username and anything else is thrown away. Since we know this is a unique field, there should only be one result, so nothing is really lost.

In the second, we directly specify the first element.

In the third, search is being called in scalar context, so it will return an iterator. We immediatly grab first result and throw the iterator away. This one will probably fail with errors like "calling method on undefined value" if there were no results.

I usually use the first method.

----
I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer

:(){ :|:&};:

Note: All code is untested, unless otherwise stated

Replies are listed 'Best First'.
Re: Re: Class::DBI 'distinct' records
by grazer (Sexton) on Oct 21, 2003 at 17:04 UTC
    Thanks for the helpful replies so far. I think that maybe I wasn't entirely clear, however. I was thinking of returning a list of distinct objects:
    table units: name location ------------------ foo_unit 1 foo_unit 2 bar_unit 1 baz_unit 3
    I was hoping to find something like:
    $iterator = Package::units->search_distinct(name); while ($iterator->next) { print }; foo bar baz
    While the first suggestion will allow me to do this (thank you), I was hoping that I could find a way to do it without hardcoding each individual query into the class.

    Regarding the schema: It is part of an existing project that cannot (easily) be changed.