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

Hello Monks, I seek you great wisdom. I'm fighting with a regex. The code:
while(defined ($file = readdir(DIR))) { next if $file =~ /^\.\.?$/; if ($file =~ /_s_/) { $file = "../human/chr".$c.".fa/$file"; foreach $tool (@$tools) { print $file,"\n"; # <------ line 1 $tool =~ s/<infile>/$file/; # <------ line 2 print $tool,"\n"; # <------ line 3 } } }
Line 1 prints what I want. Line 3 prints only the first occurance of $file, so I'm guessing that the regex is only being compiled once with the first $file it "sees". My question: How the heck do I get the substitution to work for each value of $file, not just the first? Thanks Monks.

Replies are listed 'Best First'.
Re: Substitution operator troubles
by chromatic (Archbishop) on Jun 03, 2003 at 21:11 UTC

    You're changing the array elements in-place. Once you've substituted away <infile>, it's gone for good. You could instead work on copies of the array elements:

    foreach my $tool (@$tools) { my $edit_tool = $tool; $edit_tool =~ s/<infile>/$file/ or next; }
Re: Substitution operator troubles
by cbro (Pilgrim) on Jun 03, 2003 at 20:56 UTC
    As far as I can tell you are only missing the global flag. That is:
    $tool =~ s/<infile>/$file/;
    Should be:
    $tool =~ s/<infile>/$file/g;