in reply to Re: Regular Expression Problem
in thread Regular Expression Problem

Here is what I consturcted from your example. However, it only returns the first line where there is a creat table statment. I get nothing like what you got. Could you please take a look and let me know where I went wrong.
Thanks, Bobby

#!/usr/bin/perl -w use strict; my $file = "go.txt"; print "\nOpening $file\n"; open(FILE, "< $file") || die "OLD FILE ERROR: Unable to open file: $!\ +n"; open(OUT, "> $file.new") || die"NEW FILE ERROR: Unable to create new f +ile: $!\n"; while (<FILE>) { my $data = join('', <FILE>); $data =~ s/(CREATE TABLE "SO"\.")([^"]+)(.+)(PRIMARY KEY)/$1 $2 $3 + CONSTRAINT PK_$2 $4/ms; print OUT; } print "Closing $file\n"; close(OUT) || die "Unable to close OUT file: $!\n"; close(FILE) || die "Unable to close OLD file: $!\n";

Replies are listed 'Best First'.
Re: Re: Re: Regular Expression Problem
by dakkar (Hermit) on Nov 26, 2002 at 21:26 UTC

    First, a note: the join operator is already reading the whole file into memory (the <FILE> is evaluated in list context, so it returns all the lines from the file), so there is no need for the while loop. You should just say:

    #!/usr/bin/perl -w use strict; my $file = "go.txt"; print "\nOpening $file\n"; open(FILE, "< $file") || die "OLD FILE ERROR: Unable to open file: $!\ +n"; open(OUT, "> $file.new") || die"NEW FILE ERROR: Unable to create new f +ile: $!\n"; my $data=join('',<FILE>);

    Anyway, there is an error in the regexp, and one in the modifiers. The line should be:

    $data =~ s/(CREATE TABLE "SO"\.")([^"]+)(.+?)(PRIMARY KEY)/$1$2$3CONSTRAINT PK_$2 $4/msg;

    I changed two things:

    • I changed from (.+) to (.+?), so that it matches the shortest string. Otherwise, when there are more than one "CREATE TABLE" in the file, it would match the first "CREATE" with the last "PRIMARY KEY".
    • I added the g modifier, so that every match will be changed.

    And, of course, then you have to print the result:

    print OUT $data; print "Closing $file\n"; close(OUT) || die "Unable to close OUT file: $!\n"; close(FILE) || die "Unable to close OLD file: $!\n";
    -- 
            dakkar - Mobilis in mobile