in reply to Substitute array value in regular expression

Hi,
it seems to do what you want (although I don't think $_.=<DOC>; is really what you want... (append to $_ ?) better using while(defined($_=<DOC>))

#!C:/Activeperl/bin/perl.exe use strict; use warnings; my @final_array=qw/test1 test2 fred/; #open(DOC,'sample_testing'); while(defined($_=<DATA>)){ #$_.=<DOC>; <- why are you appening? foreach my $value (@final_array) { s/$value/pagingRAC/g; } print $_; } __DATA__ this is a test this line contains test1 and test2 fred bassett is a dog but I can't spell his name.

Prints

this is a test this line contains pagingRAC and pagingRAC pagingRAC bassett is a dog but I can't spell his name.

HTH - mark

Edit by tye: Change PRE to CODE around not-short lines

Replies are listed 'Best First'.
Re: Re: Substitute array value in regular expression
by ctilmes (Vicar) on Dec 30, 2003 at 12:47 UTC
    while(defined($_=<DATA>))
    can be this:
    while (<DATA>)

    also check open() for error:

    open(DOC,'sample_testing') or die "Can't open input file: $!";
Re: Re: Substitute array value in regular expression
by bschmer (Friar) on Dec 30, 2003 at 12:51 UTC
    If you want to rid yourself of the for loop every time you go through the while you could build up a combined regular expression match before entering the loop....something like:
    use strict; use warnings; my @final_array=qw/test1 test2 fred/; my $regexp = "(" . join("|", @final_array) . ")"; while(<DATA>){ s/$regexp/pagingRAC/g; print $_; } __DATA__ this is a test this line contains test1 and test2 fred bassett is a dog but I can't spell his name.
    This makes it a little cleaner for the eye.
Re: Re: Substitute array value in regular expression
by Anonymous Monk on Dec 30, 2003 at 12:58 UTC
    Hi,
    my @final_array=qw/test1 test2 fred/;
    How can I define array in this way when I making the array dynamically .
    I search any "ps" file and then feeds the array from the search performed on the "ps" file.
    So the search pattern is based on the array value and i can't prefix it using qw.
    So how can I declare the pattern now using qw dynamically.
    Thanks for ur previous file .
      Looks like you need to read the perlop documentation on CPAN and understand the meaning of qw (Quoted Words). What qw does is to build a list, not to construct search patterns.

      my @array = qw/ element1 element2 element3 /;
      is equivalent to
      my @array = (); push @array, 'element1'; push @array, 'element2'; push @array, 'element3';
      Given that your @final_array is already setup earlier, all you need to do is to build the combined search pattern with join:
      my $pattern = join '|', @final_array;
      Why do I want to join the patterns with '|'? Because effectively I want to build a regular expression like below:
      s/pattern1|pattern2|pattern3/replace/g; # which is equivalent to my $patterns = "pattern1|pattern2|pattern3"; s/$patterns/replace/g;