Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

s/// substitution problem in a regex

Status
Not open for further replies.

hubud

Instructor
Oct 18, 2002
123
GB
Hi, I've the following snippet of code;

foreach my $match (@matchlist) {

if ($hndlread =~ /$match/) {

$match =~ s/ORA/Oracle based error, see log file for details/;
push (@temp, "$space$cause$match");
}

}

My understanding is that the above says, if $match contains ORA then replace with "Oracle base....." etc. This then gets pushed to @temp instead of "ORA".

However what I'm seeing is that on the first ORA detection in the @matchlist array it works fine. However this little loop runs in a bigger foreach loop, and on subsequent loops through this one the substitution does not find the ORA match and prints out nothing.

My guess is that $match is permanently replaced but I don't understand why

cheers

simmo
 
Yep! You're right. A foreach loop isn't just a for loop that automatically tells you each element of the array you're cruising through; it is actually implicitly referencing that element of the array. If you change it, it changes that element.

So, in your above code, let's say we're in the first iteration (where $match equals $matchlist[0]). If you do:

$match = "Hello";

$matchlist[0] now equals "Hello".

HTH,

Nick
 
Right I follow, so if I drop the array value into another variable prior to the s/// then the array will be left intact.

I'll try it tomorrow.



cheers

simmo
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top