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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.