Tcl Source Code

View Ticket
Login
Ticket UUID: 1490503
Title: regexp within foreach loop matches wrong
Type: Bug Created on: 2006-05-17 20:30:07
Submitter: sachulka Assigned to: msofer
Subsystem: 47. Bytecode Compiler Severity:
Priority: 5 Medium Last modified: 2006-05-18 15:06:22
Status: Closed Closed by: msofer
Resolution: Invalid Closed on: 2006-05-17 20:59:37
Version: obsolete: 8.4.13
Description:
I recently upgraded from Tcl8.3 to Tcl8.4.13 on 
solaris and discovered this difference which does not 
seem right. 

here is my little program:

proc send_user { x } { puts $x }
set alarmRecord [list "abc: def" "ALARM 1: blah" "ghi: 
jkl" "ALARM 2: fjdasl"]
foreach record $alarmRecord {
   if [regexp {(ALARM)[^:]+([0-9]+)} $record match key 
value] {
      send_user ">KEY $key VALUE $value\n"
   } elseif [regexp {([^:]+):(.*)} $record match key 
value]  {
      send_user "KEY2 $key VALUE $value\n"
   }
} 

Here are the results, the key and value are different 
for different Tcl versions:
sapphire:~/thuyscripts {ewuthle_eusbd00250}> tclsh8.3
KEY2 abc VALUE  def
 
>KEY ALARM VALUE 1
 
KEY2 ghi VALUE  jkl
 
>KEY ALARM VALUE 2

sapphire:~/thuyscripts {ewuthle_eusbd00250}> tclsh
% info tclversion
8.4
KEY2 abc VALUE  def
 
>KEY ALARM 1 VALUE  blah
 
KEY2 ghi VALUE  jkl
 
>KEY ALARM 2 VALUE  fjdasl

So if regexp is in the foreach loop and the same 
variables (key/value) are used inside if - regexp does 
not match correctly.
User Comments:
msofer added on 2006-05-18 03:59:37:
Logged In: YES 
user_id=148712

The bug is actually in Tcl8.3 (although I did not confirm
the behaviour there), the behaviour in 8.4 is correct.

Your script is missing some braces in order to perform
according to your expectation: it should be

  if {[regexp ...]} {
      send_user ">KEY $key VALUE $value\n"
  } elseif {[regexp ...] {
      send_user "KEY2 $key VALUE $value\n"
  }

Please note that the conditions to 'if ... elseif' are
enclosed in braces. This means that they are passed to 'if'
as strings; when 'if' evals the first condition and finds it
is true, it never evaluates the second.

In your script as posted, both regexp's are evaluated
*before* they are passed as arguments to 'if'; so, even when
the first regexp matches, the values $key and $value are set
by the second regexp.

nobody added on 2006-05-18 14:57:49:
Logged In: NO 

See also bug 219166, it was fixed in 8.4a4