stonecolddevin has asked for the wisdom of the Perl Monks concerning the following question:
Hello good monks.
I've run into a problem with my best code and project so far.
It's not necessarily erroneous code, oh no, it's bigger than that. It's my code elegance and code efficiency that I'm having troubles with.
By looking at my code, one should be able to clearly see my objective: retrieve the necessary data from their respective tables, and package them up all nice for printing to the browser.
Wonderful, dandy, works, and everyone is happy. Yea, except for the fact that I copy and pasted the same block of code n times for each piece of data I wanted.
Can a brutha get some help?
Thanks in advance,
dhoss
In essence, I'd like to be able to compact all these here for loops into one grab of the data. I can't think of a way to do this, of course, so I've come to you, the wise monks of the Monastery
bows gratefully
#!perl -w use strict; use PL; my $end; my $start ; my $obj = PL->new; my $q = $obj->CGI; $obj->Template->file ("tmpl/main.tmpl"); my @r_data = (); my @loop_data = (); my @c_data = (); my @ids = $obj->DBI->Quote->sql_ids; #my $quote = $obj->DBI->Quote->retrieve(rand @ids ); my @info = $obj->DBI->Entries->retrieve_from_sql(qq{ hidden = 'n' ORDER BY date desc LIMIT 1 }); my @comments = $obj->DBI->Replies->retrieve_from_sql(qq{ hidden = 'n' ORDER BY date desc LIMIT 5 }); my @recent = $obj->DBI->Entries->recent; print $q->header; for (@comments) { my %data; $data{c_title} = $_->title; $data{author} = $_->author; $data{id} = $_->thread_id; $data{c_id} = $_->id; push @c_data, \%data; } for (@info) { my %data; my $sth = $obj->DBI->Replies->sql_count; $sth->execute($_->id); my $r = ($sth->fetchrow_array)[0]; $data{author} = $_->author; $data{content} = $_->content; $data{title} = $_->title; $data{id} = $_->id; $data{date} = $_->date; $data{count} = $r; push @loop_data, \%data; } for (@recent) { my %data; $data{author} = $_->author; $data{title} = $_->title; $data{id} = $_->id; $data{date} = $_->date; push @r_data, \%data; } if ( $q->param('view') =~ m/last5/ ) { ## Kinda redundant...but oh well, I'll update it later. my @loop_data = (); my @info = $obj->DBI->Entries->retrieve_from_sql(qq{ hidden = 'n' ORDER BY date desc LIMIT 5 }); for (@info) { my %data; my $sth = $obj->DBI->Replies->sql_count; $sth->execute($_->id); my $r = ($sth->fetchrow_array)[0]; $data{author} = $_->author; $data{content} = $_->content; $data{title} = $_->title; $data{id} = $_->id; $data{date} = $_->date; $data{count} = $r; push @loop_data, \%data; } print $obj->Template->format ( { title=>"Devin's Journal", body=> \@loop_data, recent_c => \@c_data } ); } else { print $obj->Template->format ( { title=>"Devin's Journal", body=> \@loop_data, recent_c => \@c_data, show => $q->param ? 1 : 0 } ); }