For most of the duplication you avoid with your fetch_count function, DBI has a built-in way of avoiding it: whenever you've got a query on which ->fetch_... is only invoked once, you can skip the separate ->prepare and ->execute by using a $db->select_... method.

So the 4 active lines in your function become just 1:

sub fetch_count { my ($db, $table) = @_; $db->selectrow_array("SELECT COUNT(*) FROM $table"); }

It probably isn't worth writing a function for that, since there isn't that much duplication without it:

my $row1 = $dbh->selectrow_array('SELECT COUNT(*) FROM table_one'); my $row2 = $dbh->selectrow_array('SELECT COUNT(*) FROM table_two');

But you could always put it in some sort of loop:

my ($row1, $row2) = map { $dbh->selectrow_array("SELECT COUNT(*) FROM $_") } qw<table_one table_two>;

(By the way, I think your ->fetch_arrayref is a typo.)

Smylers


In reply to Re^2: prepare statement within DBI by Smylers
in thread prepare statement within DBI by Paulster2

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.