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:
  1. Declare variables close to where they are first used.
  2. Avoid looping over the same set multiple times.
  3. Be willing to use loop control.
  4. Have error checks as we are told in perlstyle.
  5. Use 3 arg open (see Two-arg open() considered dangerous for why).
  6. If you're going to use $_, use $_.
  7. Being willing to use $. allows you to avoid maintaining your own index.
  8. 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.
  9. Avoid having lots of empty cases on your conditionals just to say "do nothing". It should be obvious that missing cases do nothing.
  10. Interpolation is good. Use it.
  11. Don't build up a data structure just to print it later, print it the first time!
  12. 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.


In reply to Re: GOTO statement. A better way? by tilly
in thread GOTO statement. A better way? by Win

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.