Translating Perl to Python

前端 未结 8 1416
[愿得一人]
[愿得一人] 2021-01-30 07:50

I found this Perl script while migrating my SQLite database to mysql

I was wondering (since I don\'t know Perl) how could one rewrite this in Python?

Bonus point

8条回答
  •  北荒
    北荒 (楼主)
    2021-01-30 08:03

    Here is a slightly better version of the original.

    #! /usr/bin/perl
    use strict;
    use warnings;
    use 5.010; # for s/\K//;
    
    while( <> ){
      next if m'
        BEGIN TRANSACTION   |
        COMMIT              |
        sqlite_sequence     |
        CREATE UNIQUE INDEX
      'x;
    
      if( my($name,$sub) = m'CREATE TABLE \"([a-z_]*)\"(.*)' ){
        # remove "
        $sub =~ s/\"//g; #"
        $_ = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n";
    
      }elsif( /INSERT INTO \"([a-z_]*)\"(.*)/ ){
        $_ = "INSERT INTO $1$2\n";
    
        # " => \"
        s/\"/\\\"/g; #"
        # " => '
        s/\"/\'/g; #"
    
      }else{
        # '' => \'
        s/\'\'/\\\'/g; #'
      }
    
      # 't' => 1
      s/[^\\']\K\'t\'/1/g; #'
    
      # 'f' => 0
      s/[^\\']\K\'f\'/0/g; #'
    
      s/AUTOINCREMENT/AUTO_INCREMENT/g;
      print;
    }
    

提交回复
热议问题