in reply to regular expression across lines?

Add the m switch.
$stmt =~ m/^FROM\s+(\S+)$/mgs;
I have created a simple example below -
use strict; use warnings; my $sql = q{ SELECT id FROM table WHERE name like 'A%' }; my ($table) = $sql =~ m/^FROM\s+(\S+)$/mgs; print "$table\n";
And the output is as expected -
table
And of course if you want to capture multiple table names, with FROM on the same line, etc, the regular expression will be more complex, but that is out of scope.

Replies are listed 'Best First'.
Re: Re: regular expression across lines?
by Anonymous Monk on Dec 03, 2003 at 00:02 UTC
    Thanks for your suggestion. I have a print statement in my code following the regular expression:
    print "'$tablename'\n";
    
    and the interpreter scolds me with Use of uninitialized value in concatenation (.) or string when I try your regular expression which focuses on only the line comprising the FROM clause.

    I'm still baffled...

      Drop the g switch. And then modify your regex to capture table names with \w+ instead of \S+.
      use strict; use warnings; my $stmt0 = "SELECT table.field0, table.field1\nFROM table0;\n"; my $stmt1 = "SELECT table.field0, table.field1\nFROM table1\nWHERE fie +ld0 = 'foo';\n"; my $nameA = $1 if $stmt0 =~ m/^FROM\s+(\S+)$/ms; my $nameB = $1 if $stmt1 =~ m/^FROM\s+(\S+)$/ms; my $name0 = do { $stmt0 =~ m/^FROM\s+(\w+)(;*?)$/ms; $1 }; my $name1 = do { $stmt1 =~ m/^FROM\s+(\w+)(;*?)$/ms; $1 }; print "table name A ='$nameA'\n"; print "table name B ='$nameB'\n"; print "table name 0 ='$name0'\n"; print "table name 1 ='$name1'\n";
      And the output is -
      table name A ='table0;' table name B ='table1' table name 0 ='table0' table name 1 ='table1'
      Notice that in table name A, there is a ';' because of the ; character. The new regex is capable of filtering it out.

      My bad. I tried the following:
      $tablename = $1 if $stmt =~ m/^FROM\s+(\S+)/mgs;
      #$tablename =~ s/;//g;
      print "'$tablename'\n";
      
      but I am back to table; as to what is assigned to $tablename. I guess I need to resort to refining the character class I want to save. Thanks again.