I need to convert a document of SQL statements to a ColdFusion document. I only have a little experience with Regular Expressions and I am Perl super-newb (I just taught myself
From perlvar.html docs:
$/
The input record separator, newline by default. This influences Perl's idea of what a "line" is. Works like awk's RS variable, including treating empty lines as a terminator if set to the null string. (An empty line cannot contain any spaces or tabs.)
If you use $/
, it should always be local.
I personally would do it like this:
my $file = join '', <DATA>
$file =~ s/.../.../eg;
But you can do it like below, but you must include the /g
modifier.
Look at the >>>
chunks Perl is grabbing. When $/ is set to ''
, it uses a blank line as a record separator.
use strict;
use warnings;
my $num = 0;
{
local $/ = '';
while (<DATA>)
{
print ">>> '$_'\n\n";
s/(INSERT[\s\S]*?;|DELETE[\s\S]*?;|UPDATE[\s\S]*?;|SELECT[\s\S]*?;)/'<!--- SQL Number: ' . ++$num . ' ' . '<p> ' . $1 . "<\/p> --->\n"/eg;
print;
}
}
__END__
You can take advantage of the fact that the individual sql statements in your input file are terminated by a semi-colon character. Set the record input separator to a semi-colon $/ = ';'
in your perl script and then it will read one complete sql statement on each read of STDIN, regardless how many actual lines it spans.
#!/usr/bin/perl -w
use strict;
$/ = ';';
my $num = 0;
while (my $sql = <>) {
$sql =~ s/^\s+//;
printf "<!--- SQL Number: " . ++$num . " <p>$sql</p> --->\n" if $sql;
}
Once you have a ;
with in the statement you are going to hurt. Use a dedicated tool like SQL::SplitStatement, this works precise.