# use this form of foreach instead of 'my $FH = $_' foreach my $FH (@files) { # use 3-arg form of open() for safety, and deal with # being unable to open the file. open my $FILE, '<', $FH or die("Cannot read $FH: $!"); # deal with each line of the file. while loop exits # when EOF is reached. my $batch; OUTER: while () { $batch .= $_; # cat this line to $batch # if we just read a line that's 'GO', run the batch and # reset the variable $batch to be empty if (m/^\s*go\s*$/i) { $dbh->do($batch); # you should check for and deal with DBI errors here $batch = ''; } } # if we didn't reach a 'GO', there will be stuff in $batch, so # we should report that fact. warn "File '$FH' contained unexecuted commands:\n$batch\n"; }