I read the first line of cchampion's reply but not the rest, so I thought I'd take a stab myself.

Like the OP, I presume the variable $dbh, the array @userdata and the subroutine error() to be predefined. However, it appears that the OP is using this subroutine to set a global variable called $sth from which results are later retrieved. I find this upsetting so I'm going to have the subroutine termgrades() return it instead, and return undef in case of errors. I also changed the messages so that an prepare error would not return the same message as an execute error.

my %quarternames = (1 => 'first', 2 => 'second', 3 => 'third', 4 => ' +fourth'); my %tablenames = map { $_ => "$quarternames{$_}quarter" } keys %quarternames; my %queries = map { $_ => " SELECT * FROM $tablenames{$_} WHERE userid = ? AND period = ? AND gradetype = +? " } keys %tablenames; sub termgrades { my $period = shift; my $quarter = shift; my $sth; return undef unless exists $queries{$quarter}; $sth = $dbh->prepare_cached($queries{$quarter}) or do { error ("2", "Could not prepare query for $quarterna +mes{$quarter} quarter for $userdata[0]: $dbh->errstr"); return undef; }; $sth->execute($userdata[0], $period, 2) or error("2", "Could not execute query for $quarternames{$qua +rter} quarter for $userdata[0]: $sth->errstr"); return $sth; }

Update: Made hash initialization slightly more clever.


In reply to Re: I present to you... Horrible code! by Errto
in thread I present to you... Horrible code! by BUU

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.