0

I am trying to replace many array element with another corresponding array element in a file, but its taking ages to execute. Is there a simpler approach ? Below is my code:

open( my $in,  '<', "Test.txt")  or die "cannot open Test.txt $!";
open( my $out, '>', "TestFinal.txt") or die "cannot create TestFinal $!";
while( <$in>)
{ 
    for(my $i=2 ; $i<=$LastRowGlossary; $i++)
    {
        s/$variable[$i]/$vardescription[$i]/g;
    }
    for(my $j=2 ; $j<=$LastRowTable; $j++)
    {
        s/$COVERAGE_TYPE_CODE[$j]/$TCOVERAGE[$j]/g;
        s/$CVG_TEST_CRIT_CD[$j]/$TCVG_TEST_CRIT_TYP[$j]/g;
    }

    print {$out} $_;

}
close $in; 
close $out;

Please advise.

4
  • All the arrays elements are being picked up from an excel sheet. eg: $variable[2] contains "TEMP" $vardescription[2] contains "Temperature" and so on. And the size of each array goes upto 60 or maybe more. Commented Oct 17, 2012 at 12:02
  • You should post the content of Test.txt. Commented Oct 17, 2012 at 12:08
  • You should probably use some precaution to avoid partial substitutions, such as CAR being replaced in CARCASS. Commented Oct 17, 2012 at 13:02
  • Oh Yes! :) ($variable[$i]\b) does the job. Commented Oct 17, 2012 at 13:10

1 Answer 1

5

Sometimes, generating the regex can help:

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

my @variables =    qw/a b c d e f g h/;
my @descriptions = qw/A B C D E F G H/;

my %replace;
@replace{@variables} = @descriptions;

my $string = 'xaxbxcxdxexfxgxhx';

my $pattern = '(' . join('|', map quotemeta, @variables) . ')';

$string =~ s/$pattern/$replace{$1}/g;

print "$string\n";
Sign up to request clarification or add additional context in comments.

2 Comments

Very nice one...learnt quite a few things in just a single post of yours..thank you..
@choroba I tried your approach. Really a good one! But still the time taken is same.. :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.