in reply to Reusing a variable declared earlier in the same scope
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.
Now, you have a piece of reusable code. It should be pretty easy to extend if you want to pass optional parameters in.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;
|
|---|