Sorting Perl with Class::DBI -
you have following table called pets:
name age pet ------------------------ carol 25 null stean 23 cat mel 24 dog rich 24 rabbit
in mysql database on server mydbserver user of 'user' password of 'password'.
do following:
1) create class::dbi
connection database above credentials ( dbi.pm ).
2) create class table pets ( pet.pm )
3) create program prints names of people in pets table , kind (if ) of pet he/she has sorted name age.
here code wrote.....
#!/usr/bin/perl package pet::dbi; use dbi; use strict; use base 'class::dbi'; pet::dbi->set_db('main','dbi:mysql:dname', 'user', 'password') or die $dbi::errstr "\n"; 1; package pet::pets; use base 'pet::dbi'; use strict; use warning; pet::pets->table('pets'); pet::pets->columns(all => qw/name age pet/); 1; use pet::pets; @pets = pet::pets->retrieve_all; (sort {$a->name cmp $b->name} || {$a->age <=> $b->age} @pets) { print "name:".$_->name ' => '."age". $_->age"\n"; } 1;
it's correct, there's number of small problems.
it's not necessary load dbi, class::dbi take care of you.
you should using connection
instead of set_db("main", ...)
. set_db
comes ima::dbi , it's not polite (or necessary) peek under hood that.
although isn't directly documented in class::dbi (it should be), inherited ima::dbi, there's no need check dbi errors. raiseerror on , if connection fails throw error.
you have typo, use warning;
instead of use warnings;
.
unless have stitched 3 files post, if code in 1 file 1;
statements nothing. use pet::pets
not work because there no pet/pets.pm
file. don't have use class in same file.
in general, avoid using $_
if don't have to, many things can quietly use or change it. instead, give loop proper variable for $person
.
sort
takes 1 block, you're correct. should sort { ($a->name cmp $b->name) || ($a->age <=> $b->age) } @pets
to avoid reading whole, potentially large, table memory, sorting should done in database order name asc, age asc
, retrieved row @ time using iterator. unfortunately, retrieve_all not support options. can use retrieve_from_sql
add arbitrary sql end of basic select. my $all_people = pet::pets->retrieve_from_sql("order name asc, age asc");
data sorted , can read row @ time. while( $person = $all_people->next ) { ... }
you're missing .
in "age". $_->age"\n"
.
null values in database come undef. you'll want check if $_->pet
defined , if not use other string "no pet"
or blank ""
.
you're printing person's age, question asks pet.
otherwise, should work.
but really, tell whomever gave homework stop telling people use class::dbi. can email me if like, schwern@pobox.com.
Comments
Post a Comment