How do I use Perl and Regular Expressions to convert a SQL document to ColdFusion script?

后端 未结 3 1739
陌清茗
陌清茗 2021-01-27 11:49

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

相关标签:
3条回答
  • 2021-01-27 12:04

    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__
    
    0 讨论(0)
  • 2021-01-27 12:16

    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;
    }
    
    0 讨论(0)
  • 2021-01-27 12:19

    Once you have a ; with in the statement you are going to hurt. Use a dedicated tool like SQL::SplitStatement, this works precise.

    0 讨论(0)
提交回复
热议问题