
BillKSmith
Veteran
Feb 4, 2013, 8:21 AM
Post #6 of 7
(30969 views)
|
My previous post was correct, but I failed to understand an important detail. The $_ in grep is not a program variable, but rather an alias for one element of the input array at a time. A separate match position is maintained for each element. A match is never found for any element except the fifth. The position for those elelments is reset every time. In your first grep, a match is found for the fifth element. Its position is advanced past the match. The second grep does not find a match because there are not any more matches. The position is reset. The third grep is now has the same situation as the first and gets the same result. You can get the result you expected by resetting the position of the fifth element each time.
#!/usr/bin/perl -w print qq($]\n); @NewCodes = (1,2,3,4,5,6,7,8,9); $oldyear = 6; @sameYear = grep(/$oldyear/g, @NewCodes); print qq(old year <$oldyear> high index in sameYear $#sameYear\n); @sameYear = (); pos($NewCodes[5]) = 0; @sameYear = grep(/$oldyear/g, @NewCodes); print qq(old year <$oldyear> high index in sameYear $#sameYear\n); @sameYear = (); pos($NewCodes[5]) = 0; @sameYear = grep(/$oldyear/g, @NewCodes); print qq(old year <$oldyear> high index in sameYear $#sameYear\n); OUTPUT:
5.016001 old year <6> high index in sameYear 0 old year <6> high index in sameYear 0 old year <6> high index in sameYear 0 Good Luck, Bill
|