in reply to Reusing a variable declared earlier in the same scope

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?