Thursday, July 12, 2012

Easiest Example for upvar in TCL


Usage:

Used when we have to change the value of a global variable from inside a procedure’s scope

Example
proc example {one two} {
upvar $one local1
upvar $two local2

set local1 Kavitha
set local2 Anbarasu

}

set glob1 David
set glob2 Beckam

puts $glob1
puts $glob2\n

example glob1 glob2
puts $glob1
puts $glob2

Output
David
Beckam

Kavitha
Anbarasu

In the above example we are able to change the value of two global variables glob1 and glob2 from within a procedure

Usage of ?: in TCL


Usage:

?: is used in sub patterns in a regexp
When ever you don’t want a particular subpattern to be included as a sub-pattern use “?:” in front of the sub-pattern

Example:

set string "Projects: Brocade Cisco Fujitsu"

regexp "Projects: (Brocade|Cisco) (?:Fujitsu|Juniper|Cisco) (Fujitsu|Juniper)" $string sub1 sub2 sub3

puts "$sub1\n$sub2\n$sub3\n"

In the above example, the output will be

Projects: Brocade Cisco Fujitsu
Brocade
Fujitsu

The pattern “Cisco” does not come under sub pattern as “?:” is given

The output without ?: would be


Projects: Brocade Cisco Fujitsu
Brocade
Cisco

regsub Command


Regsub Usage

Replaces a value with a given value

Syntax:
regsub “<actual value in the string>”  $string “<value to replace>” <newString>


Example:

set string "My name is Kavitha"

regsub "Kavitha" $string "Mythri" name2
puts "$name2"

Output

My name is Mythri