I think it looks pretty good. Your use of DBI, its shortcut methods (
selectall_arrayref and
fetchall_arrayref), and the Slice options is spot-on: this is exactly why these methods are there.
I only have some stylistic comments, prompted by the fact that add_subject_loop modifies one of its arguments.
- I would try to remove the side-effects, and make it a proper function
- I would try to move the sql strings and the preparation of the subject handle out of get_category_loop
I believe that would improve the structure of your program, and increase its maintainability. Abstracting away the lower-level sql stuff is a good idea. See for instance Perl Hacks for some pointers.
I'm also a big fan of prepare_cached, since it can remove the need of global $sth variables.
Here's a suggested refactoring:
sub get_category_loop {
return [
map {
$_->{subject_loop}
= get_subject_loop( delete $_->{category_id} ); # dele
+te returns the value that was in the hash
$_
}
@{ $dbh->selectall_arrayref(sql_category(), {Slice => {}}) }
];
}
sub get_subject_loop {
my $category_id = shift;
my $sth = $dbh->prepare_cached( sql_subject() );
$sth->execute($category_id);
return $sth->fetchall_arrayref({});
}
sub sql_category {
return q{
SELECT category_id,
category_name
FROM category
ORDER BY category_id
};
}
sub sql_subject {
return q{
SELECT subject_id,
subject_name
FROM subject
WHERE category_id = ?
ORDER BY subject_name
};
}
I'm not so sure anymore if the
map is justified. I feel a foreach loop would probably be easier to read now.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.