in reply to Regular Expression Problem

Not really sure what you mean by inside a while loop.
Unless you have several of these type of entries that this needs to be done to?

Maybe something like this would do the trick?

#!/usr/local/bin/perl use strict; my $data = join( '', <DATA> ); $data =~ s/(CREATE TABLE "SO"\.")([^"]+)(.+)(PRIMARY KEY)/$1$2$3CONSTR +AINT PK_$2 $4/ms; print $data; __DATA__ CREATE TABLE "SO"."EL_HAND_RECEIPT" ( EL_ID NUMBER(20) NOT NULL, UIC VARCHAR2(6) NULL, ISSUE_RECEIPT_CD VARCHAR2(1) NOT NULL, PRIMARY KEY (EL_ID) ) TABLESPACE DATA

Outputs...

:!test.pl CREATE TABLE "SO"."EL_HAND_RECEIPT" ( EL_ID NUMBER(20) NOT NULL, UIC VARCHAR2(6) NULL, ISSUE_RECEIPT_CD VARCHAR2(1) NOT NULL, CONSTRAINT PK_EL_HAND_RECEIPT PRIMARY KEY (EL_ID) ) TABLESPACE DATA
If that doesnt help, post some code.

Wonko

Replies are listed 'Best First'.
Re: Re: Regular Expression Problem
by curtisb (Monk) on Nov 26, 2002 at 20:46 UTC

    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";

      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