my $sth =
do->("SELECT bug_id, owner, subject, status, assigned FROM BUGS");
while (
my ( $bug_id, $owner, $subject, $status, $assigned ) =
$sth->fetechrow ) {
push @{$bugTable{$bug_id}},
( $owner, $subject, $status, $assigned );
}
print "Which column would you like to sort by?\n";
print "\t Bug_ID(1), Owner(2), Subject(3) ".
", Status(4) or Assigned_To(5) ?: ";
my $input = ;
SWITCH: for ($input) {
/1/ && do {
@srtArr = sort { $a <=> $b } keys %bugTable;
last;
};
/2/ && do {
@srtArr =
sort { ${$bugTable{$a}}[0] cmp ${$bugTable{$b}}[0] } keys %bugTable;
last;
};
/3/ && do {
@srtArr =
sort { ${$bugTable{$a}}[1] cmp ${$bugTable{$b}}[1] } keys %bugTable;
last;
};
/4/ && do {
@srtArr =
sort { ${$bugTable{$a}}[2] cmp ${$bugTable{$b}}[2] } keys %bugTable;
last;
};
/5/ && do {
@srtArr =
sort { ${$bugTable{$a}}[3] cmp ${$bugTable{$b}}[3] } keys %bugTable;
last;
};
} # End of SWITCH.
for my $bug_id ( @srtArr ) {
print " @{$bugTable{$bug_id}} \n";
}
-- Randal L. Schwartz, Perl hacker
Be sure to read my standard disclaimer if this is a reply.
While I agree that one should let db sort for him/her, the code is then too simple and straight to be a snippet. You pointed a point, but quickly missed another one.
That's not demonstrated in this example, but I've done this before.
my $sql = "SELECT bug_id, owner, subject, status, assigned FROM BUGS ORDER BY $field";Second, i personally would prefer selectall_hashref .. simplifies the database retrieval, and makes the sorting clearer and trivial .. (also just a hash works instead of a "switch")
my $bugTable = $dbh->selectall_hashref("SELECT bug_id, owner, subject, status, assigned FROM BUGS");
my %numSorts = ( 1=>'bug_id' );
my %strSorts = ( 2=>'owner', 3=>'subject', 4=>'status', 5=>'assigned' );
my $input = ;
chomp $input;
my @srtArr = keys %$bugTable;
if( exists $strSorts{$input} ){
@srtArr = sort { $bugTable->{$a}->{ $choices{$input} } cmp $bugTable->{$b}->{ $choices{$input} } } @srtArr;
}elsif( exists $numSorts{$input} ){
@srtArr = sort { $bugTable->{$a}->{ $choices{$input} } <=> $bugTable->{$b}->{ $choices{$input} } } @srtArr;
}
print " @{$bugTable->{$_}} \n" for @strArr;
Because of his itch hands, that's all. It is a good practice for certain people, so don't stop them from doing that. There always some people hands itch, not a bad thing, not at all.
On the other hand, let db do the sort isnot always the solution. For example order by doe snot play with things like limit in some db implementation. In those cases, you are forced to do the order by yourself. Of course nested query is also a solution. Voila.
perlmonks.org content © perlmonks.org and Anonymous Monk, davidrw, jeremyh, merlyn, pengwn
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03