peter cooke peter cooke - 3 months ago 9
Perl Question

Matching modifying characters after pattern

I did this almost 20 years ago. so forgot much about perl and not finding answer in google.

I have a file with many Times Ten DB "create hash index" statements of the form

create unique hash index on MYSCHEMA.MYTABLE (Col1, Col2) pages=####;
create hash index on MYSCHEMA.ANOTHER_TABLE (Col1, Col2) pages=####;


I have an associative array with table names and the desired values for "pages=###".

I have properly read the line into a string variable.

I need to know how to get the table name following "index on MYSCHEMA." into a variable.

Also How do I replace the numbers in "pages=####"

Thanks so much for your help

Peter

Answer

Use matching in a list context to extract the table name.

#!/usr/bin/perl
use warnings;
use strict;

my @lines = (
    "create unique hash index on MYSCHEMA.MYTABLE (Col1, Col2)  pages=####;\n",
    "create hash index on MYSCHEMA.ANOTHER_TABLE (Col1, Col2)  pages=####;\n"
);

my %pages = ( MYTABLE => 12,
              ANOTHER_TABLE => 42,
);

for my $line (@lines) {
    my ($table) = $line =~ /index on MYSCHEMA\.(\w+)/;
    $line =~ s/pages=####/pages=$pages{$table}/;
    print $line;
}