[NTLUG:Discuss] Perl pattern matching problem

Patrick R. Michaud pmichaud at pobox.com
Tue May 2 08:04:22 CDT 2006


On Mon, May 01, 2006 at 10:51:13PM -0500, Douglas Scott wrote:
> I have an odd problem with some Perl code.
> 
> I have two small text files.  One is a list store numbers and quantities, 
> separated by tabs.  The other contains 2 lines of text that contains patterns 
> that I wish to replace with the numbers from the other file.  I have the 
> small model file loaded into the array @Model.  
> 
> The first time through the loop the script works as expected.  But after that 
> it keeps the original values for $Order and $Count and keeps using them, no 
> matter what is read from the file. 
> 
> my ($Order, $Count); 
> 
> foreach my $Spec ( <LIST> ) 
>    { 
>    chomp $Spec; 
>    ($Order, $Count) = split /\t/, $Spec; 
>    $Count = sprintf "%04d", $Count; 
>    print "$Order, $Count\n"; 
>    foreach my $Line ( @Model ) 
>       { 
>       $Line =~ s/<stno>/$Order/g; 
>       $Line =~ s/<pc>/$Count/g; 
>       print $Line; 
>       } 
>    } 

In this last loop, note that $Line is set to "reference" each element 
of @Model directly, not a copy of it.  Thus, any changes you make to 
$Line are really changing the elements in @Model.

So, the first time through the loop, all of the <stno> and <pc>
strings in @Model are being replaced by $Order and $Count.  After
that, the strings in @Model no longer have <stno> and <pc>
substrings to replace for subsequent passes through the outer loop.

You probably want something more like:

    foreach my $Spec ( <LIST> ) 
       { 
       chomp $Spec; 
       ($Order, $Count) = split /\t/, $Spec; 
       $Count = sprintf "%04d", $Count; 
       print "$Order, $Count\n"; 
       foreach my $Line ( @Model ) 
          { 
          $x = $Line;
          $x =~ s/<stno>/$Order/g; 
          $x =~ s/<pc>/$Count/g; 
          print $x; 
          } 
       } 

Pm



More information about the Discuss mailing list