There are a few different solutions. The first (and most obvious) is $rows = $some_sth->rows;, but only for the second and subsequent.

A slightly better solution would be to create a bare scope. That could look something like:

y @AssignmentIDs = (); my $GetAssignmentID_sth=$query_dbh->prepare($SQL); $GetAssignmentID_sth->execute(); { my $rows = $GetAssignmentID_sth->rows; if($rows > 0) { while (my ($AssignmentID, $UserCount) = $GetAssignmentID_sth-> +fetchrow_array() ) { push(@AssignmentIDs, $AssignmentID); } } } my $AssignmentIDs = join(",",@AssignmentIDs); $GetAssignmentID_sth->finish();

That makes it very clear what the scope of each thing should be. I've used that on many occasions. However, there's a better way - create a subroutine to do stuff. Now, you're thinking "But each while-loop is different!" Ok - encapsulate the differences.

sub read_sql { my ($dbh, $sql, $callback) = @_; my $sth = $dbh->prepare( $sql ); $sth->execute(); return unless $sth->rows; while ( my @row = $sth->fetchrow_array ) { $callback->( @row ); } $sth->finish; } my @AssignmentIDs; # You don't need the empty assignment. read_sql( $dbh, $sql, sub { my ( $AssignmentID, $UserCount) = @_; push @AssignmentIDs, $AssignmentID; }); my $AssignmentIDs = join ',', @AssignmentIDs;
Now, you have a piece of reusable code. It should be pretty easy to extend if you want to pass optional parameters in.

My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

In reply to Re: Reusing a variable declared earlier in the same scope by dragonchild
in thread Reusing a variable declared earlier in the same scope by reluctant_techie

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.