my $last_sql_file; while (my $line = <$LOG>) { chomp $line; $last_sql_file = $1 if $line =~ /^executing: \@(.+)/; if ($line =~ /^ERROR at/) { unlink $last_sql_file if -f $last_sql_file; # don't try to delete this file if it was already deleted on a previous error } }