in reply to Find Replace text with list

wa2nlinux:

I assume the part you're having trouble with is getting the regular expression into a variable and treating it as a regular expression instead of a string. If you read perldoc perlop in the section on "Quote and quote-like operators", you'll find the subsection "Regex Quote-Like Operators" which will help you.

Basically the trick is this: Once you get the regex into a string, you can use the qr operator to turn it into a reference to a regex that you can use just like a regular expression:

$ cat regex_in_str.pl #!/usr/bin/perl use strict; use warnings; my $r = "ab+c*d"; my $rRegex = qr/$r/; for my $t (qw( abcd aabbbd acccd dbca )) { if ($t =~ $rRegex) { print "MATCH: $t\n"; } } $ perl regex_in_str.pl MATCH: abcd MATCH: aabbbd $

So all you need to do is read the name and representation of your regular expression from a file, convert the representation into a reference to a regex and load your array.

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^2: Find Replace text with list
by wa2nlinux (Novice) on Feb 08, 2011 at 02:37 UTC
    How could I qw each line of file ?
    @lines=<FILE>; my $t = qw (@lines)
    not working ?
        Ok sorry for an unclear question here my problems I have 3 files : source.txt, target.txt and data. Data file contain 2 column separate by :, example for code below is /hang:code1 /hung:code2 /hong:code3 then source.txt is file text that I want to process it, I need to read all lines and compare to the data file, the source.txt is guarantee have code such as \hang \hung \hing etc (left side code from data file) then those code are replace by code1, code2 etc and write to target file ( target.txt)
        #!/usr/bin/perl use strict; use warnings; my $filename = 'data'; my $sfilename = 'source.txt'; my $tfilename = 'target.txt'; open(DFILE, $filename) or die "Could not read from $filename, program +halting."; open(SFILE, $sfilename) or die "Could not read from $filename, program + halting."; open(TFILE, "> $tfilename") || die("Cannot Open File"); while(my $SBR=<DFILE>) { my @fields = split(':', $SBR); my $rRegex = qr/$fields[0]/; my $Regexr = qr/$fields[1]/; for my $s (qw(/hang /hung /hing /heng)) { #here I need read it + as a source file, compare to data file if ($s =~ $rRegex){ print TFILE "$fields[1] "; # then write it to target file } } } close DFILE; close SFILE; close TFILE;

      wa2nlinux:

      You don't need to. I used qw just for making the example. Perhaps I should've written it like this:

      #!/usr/bin/perl use strict; use warnings; my $r = "ab+c*d"; my $rRegex = qr/$r/; while (my $t = <DATA>) { if ($t =~ $rRegex) { print "MATCH: $t\n"; } } __DATA__ abcd aabbbd acccd dbca

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.