Detlef Lindenthal wrote: > ### Richard Smith wrote: > ### "... but the previous value of $1 still seems to > ### persist." > ### > ### > ### Hi Richard, > ### > ### In RegEx, the variables $1, $2, $3 ... might carry on > ### unwanted values from previous uses. > ### How can we erase them? > ### You can do this: > > $_ = "anything"; > m,(a),; > print "\n(1.) \$1: ", $1; ## now $1 carries "a". > > ### You cannot erase the $1 variable in this way: > > # $1 = ""; > ### Error message: " # Modification of a read-only value attempted." > > ### But you can erase the $1 and $2 and $3 ... variables in this way: > > $_ = "anything"; > ### $1, $2, $3 do look for "nothing" and do find "nothing", thus > ### $1, $2, $3 are erased: > m,()()(),; > print "\n(2.) \$1: ", $1; > > > =Result: > > (1.) $1: a > (2.) $1:
There are other ways of avoiding this problem. Consider the following: #!/usr/bin/perl -l use warnings; use strict; my @array; while (<DATA>) { chomp; next unless m/(\w+)\sstring/; push @array, $1;# now we don't push a previous match into the array print; } print join ", ", @array; __DATA__ mystring the string any old string some nonmatchingstring sting like a bee stringing me along yet another string that matches results: 3:55am {3} pcp02404936pcs:/home/webdragon>$ perl -c testperl2 testperl2 syntax OK 3:55am {4} pcp02404936pcs:/home/webdragon>$ perl testperl2 the string any old string yet another string that matches the, old, another basically you can avoid the effects of this by skipping unless there's a match. also things like: ,----[ surrounding loop (foreach, while, etc) ] | #skip if no match | next unless (my $name, $date) =~ m{^\s+(\w+\s+\w+)\s+(\d+\/\d+)\s+$}i; | #do something with $name/$date... `---- mean that those two variables will not be assigned to unless the regex actually matches successfully, AND would be scoped to the loop around it thus would not persist each iteration through the loop.