why the following regular expression does not work in tcl?

advertisements

I am reading some code in TCL, the regular expression does not work,

set name "Ronaldo"

proc GET_PLAYER_INFO {player_id {player_name "$name"}} {
    global name

    regexp "$player_name" "Ronaldo is awesome" match

    puts $match
}

GET_PLAYER_INFO {1,"$name"}

in this double quotation marks, "$player_name" is replaced by "$name"? and the $name is "Ronaldo", but why it does not match?


This is not doing what you expect. Curly brances means no variable substitution within them so when you call GET_PLAYER_INFO you are setting the first parameter to the exact byte sequence contained within the braces ie: 1,"$name"

Within the procedure, player_name is set to exactly $name so your regexp line expands to:

regexp '$name' "Ronaldo is awesome" match

So it attempts to match the end of line followed by 'name'.

If you want to use a variable default parameter you should really set it to some guard value then retrieve it from an external source when not modified eg:

proc proc GET_PLAYER_INFO {player_id {player_name ""}} {
    global name
    if {$player_name eq ""} { set player_name $name }
    regexp "$player_name" "Ronaldo is awesome" match
    puts $match
}

Re-read carefully Tcl(1) paying special attention to the parts about grouping.