rsriram has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I have imported the contents of two text files into two arrarys. Array 1 @file contains the following:

<tag>line one line two line three <tag>line four

Array 2 @cmds contains the following:
\replace<tab>tag<tab>element<br>\replace<tab>it<tab>italic
I want to open the first array go through line by line and replace based on the conditions given on array 2. The output I desire should look like:
<element>line one line two line three <element>line four

I tried using the following code:
foreach(@file) { for my $x (0..$#replace) { if($replace[$x] =~ /\\replace\t(.+?)\t(.+?)\n/g) { $_ =~ s/$1/$2/g; } print $_; } }

Can someone tell me where I am going wrong?

Replies are listed 'Best First'.
Re: Help in using two arrays
by ikegami (Patriarch) on Jun 11, 2008 at 14:10 UTC

    Quickly, I might not have caught everything

    • 'g' modifier in an if is almost always wrong. It is wrong here.

    • $2 in s/.../$2/ refers to the second capture in ..., not some earlier capture by some other match or substitution operator.

    • The search expression appears to be text, not a regexe, but you use it as a regexp.

    • Using $_ in $_ =~ s/$1/$2/g; and print $_; defies the purpose of using $_.

    for my $line (@lines) { for my $replace (@replaces) { my ($s,$r) = $replace =~ /\\replace\t(.+?)\t(.+?)\n/ or next; $line =~ s/\Q$s\E/$r/g; } print $line; }

    Update: Actually, that's a bad approach since you have to keep recompiling regexps. Reverse the nesting of your loops:

    for my $replace (@replaces) { my ($s,$r) = $replace =~ /\\replace\t(.+?)\t(.+?)\n/ or next; s/\Q$s\E/$r/g for @lines; } print @lines;

    Update: Woops, I was still using $2. Switched to $r.