Untested, off of the top of my head, here is a cleaner version of the above:
#! perl -w
use strict;
use warnings;
my $outfile = "Outfile.txt";
open (OUT, "+>>$outfile") or die "Cannot append to '$outfile': $!";
FILE: while (<*.sql>) {
my $file = $_;
next FILE if $file eq 'Activate.sql';
open (my $fh, "<", $file) or die "Cannot read '$file': $!";
print "$file\n";
while (<$fh>) {
if (1 == $. and m/ALTER\sPROCEDURE\s/) {
next FILE;
}
if (
not m/INSERT INTO Message_pool/
and m/CREATE TABLE\s([A-Z|a-z|_]{1,200})\s.{0,100}/
) {
print OUT "if exists (select 1 from INFORMATION_SCHEMA.tables wh
+ere table_name = '$1') DROP TABLE $1\n";
}
}
}
Here is a list of what I changed:
- Declare variables close to where they are first used.
- Avoid looping over the same set multiple times.
- Be willing to use loop control.
- Have error checks as we are told in perlstyle.
- Use 3 arg open (see Two-arg open() considered dangerous for why).
- If you're going to use $_, use $_.
- Being willing to use $. allows you to avoid maintaining your own index.
- It is better to say (1 == $var) rather than ($var == 1) because then forgetting an = in there results in an illegal instruction rather than a nasty logic bug.
- Avoid having lots of empty cases on your conditionals just to say "do nothing". It should be obvious that missing cases do nothing.
- Interpolation is good. Use it.
- Don't build up a data structure just to print it later, print it the first time!
- I added "\n" where it seemed appropriate.
UPDATE: hv pointed out that I was still using $table_name when the data was in $1. Fixed.