user707549
user707549

Reputation:

why the following regular expression does not work in tcl?

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?

Upvotes: 0

Views: 665

Answers (2)

bmk
bmk

Reputation: 14137

In addition to patthoyts solution I have another variant here:

set name "Ronaldo"

proc GET_PLAYER_INFO [list player_id [list player_name "$name"]] {
    regexp "$player_name" "Ronaldo is awesome" match
    puts $match
}

GET_PLAYER_INFO 1 $name

The player_name argument of GET_PLAYER_INFO will get it's default value from the $name variable (but take care: $name has to exist before procedure declaration).

Upvotes: 2

patthoyts
patthoyts

Reputation: 33193

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.

Upvotes: 4

Related Questions