Você está na página 1de 19

Variables

EX : set name Mark


puts $name
unset name

info exists command can be used to check if a variable exists

EX : if { ![info exists counter] } {


set counter 0
} else {
incr counter
}

In addition, curly braces can be used to explicitly delimit the variable name (e.g. ${x})

EX : set a 0.16
set b ${a}um
puts $b => 0.16um

Lists :
EX : set myList [list Mark Travnikoff 10644002 May 15 2000]

Lists can also be created by concatenating elements together into a list

EX : set var1 4
set var2 PDE
set myList [concat $var1 $var2 ]
puts $myList => 4 PDE

Index :

EX : set myList [list Mark Travnikoff 10644002 May 15 2000]


puts [lindex $myList 0] => Mark
puts [lindex $myList 5] => 2000

Range :

EX : set var1 [list PDE Folsom Chandler Bangalore Penang]


set extractedList [lrange $var1 2 4]
puts $extractedList => Chandler Bangalore Penang

Length :

EX : set myList [list Mark Travnikoff 10644002 May 15 2000]


puts [llength $myList] => 6
Append :

EX : set var1 PDE


set var2 Folsom Chandler Bangalore Penang
lappend var2 $var1
puts $var2 => Folsom Chandler Bangalore Penang PDE

lset :

EX : set var1 [list Folsom Chandler Bangalore Penang]


lset var1 0 Austin
puts $var1 => Austin Chandler Bangalore Penang

Insert :

EX : set var1 PDE


set myList [list Folsom Chandler Bangalore Penang]
set myList [linsert $myList 1 $var1]
puts $myList => Folsom PDE Chandler Bangalore Penang

Replace :

EX : set var1 [list PDE Folsom Chandler Bangalore Penang]


set myList [lreplace $var1 1 4 FM CH BA PNG]
puts $myList => PDE FM CH BA PNG

Search :

Returns the index for the first match, or a -1 if there is no match

* Matches any quantity of any character.


? Matches one occurrence of any character.
\X The backslash escapes a special character in globbing just the way it does in Tcl
substitutions. Using the backslash lets you use glob to match a * or ?
[] Matches one occurrence of any character within the brackets. A range of characters
can be matched by using a range between the brackets. For example, [a-z] will match
any
lower case letter.

EX : set var1 [list PDE Folsom Chandler Bangalore Penang]


set index [lsearch $var1 Ch*]
puts $index => 2

To return the list value instead of the index use the inline option

EX : set var1 [list PDE Folsom Chandler Bangalore Penang]


set result [lsearch inline $var1 Ch*]
puts $result => Chandler
More lsearch options :

-all Search for all items that match & return list of matching indices.
-dictionary Compared using dictionary-style comparison. Need to use
-exact or sorted as well.
-exact Do exact string matching
-inline Return the value of the matching element instead of the index.
-integer Compare as integers.
-not Negate the match.
-real Compare as real numbers.
-regexp Use an RE (described in a later module).
-sorted Tell Tcl the list is presorted allows for faster search algorithm.
-start x Specify the start index in the list to begin searching

Sort :

By default sorts in alphabetical order (i.e. ascii order)

EX : set var1 [list PDE Folsom Chandler Bangalore Penang]


set sorted [lsort $var1]
puts $sorted => Bangalore Chandler Folsom PDE Penang

Use the integer or -real switch to sort integers or floating point numbers

EX : set var1 [list 0 -0.5 2 10 5]


puts [lsort real $var1] => -0.5 0 2 5 10

Use the -decreasing option to reverse the sorting order.

EX : set var1 [list 0 -0.5 2 10 5]


puts [lsort real decreasing $var1] => 10 5 2 0 -0.5

Use the dictionary switch to sort using dictionary-style comparison.

EX : puts [lsort dictionary {a Z b21 b22}] => a b21 b22 Z


puts [lsort ascii {a Z b21 b22}] => Z a b21 b2

Split :

EX : set myList [split /usr/intel/bin/tcl /] ;# myList = {} usr intel bin tcl


set myList2 [split 1234567 36] ;# myList = 12 45

Join :

EX : set myString [join {{} usr intel bin tcl} /]


puts $myString => /usr/intel/bin/tcl
Arrays

Arrays are associative (i.e. the index may be a string)

EX : set myArray(0) Mark


set myArray(1) Travnikoff
set myArray(2) 10644002
puts value at index 1 is $myArray(1) => value at index 1 is Travnikoff

Note that the indices of arrays do not need to be integers, they can be any string value.
This makes them similar to associative arrays or hashes in other languages

EX : set myArray(first_name) Mark


set myArray(last_name) Travnikoff

Array exists :

Returns 1 if arrayName is an array variable. Returns 0 if arrayName is a scalar variable, proc, or does not
exist

EX : set array1(0) 0
if {[array exists array1]} {
puts array1 is an array => array1 is an array
} else {
puts array1 is not an array
}

Array Size :

EX : set array1(0) 0
set array1(1) 1
if {[array exists array1]} {
puts array1 contains [array size array1] elements
} => array1 contains 2 elements

Array names :

EX : set myArray(first name) Mark


set myArray(last name) Travnikoff
set myArray(wwid) 10644002
puts myArray contains the following entries: [array names myArray]
=> myArray containst the following entries: last_name first_name wwid
Array set :

To convert a list into an associative array use the array command with the set option. Each odd member
of the list (1, 3, 5, etc) will become an index into the associative array, and the list element following
that is the value of that array member

EX : array set capitals {


France Paris
Italy Rome
Russia Moscow
Germany Berlin
Spain Madrid
Canada Ottawa
}
puts The capital of Spain is $capitals(Spain) => The capital of Spain is Madrid

Array get :

To convert an associative array into a list use the array command with the get option. Each odd member
of the list is an index of the original associative array and the even members are the value associated
with that index

EX : array set capitals {


France Paris
Italy Rome
Russia Moscow
}
puts [array get capitals] => Russia Moscow France Paris Italy Rome

Multi Dimension:

Tcl doesnt support multidimensional arrays; however, they can be simulated by concatenating multiple
indices into a single element name.

EX : set matrix(1,1) 200


set matrix(1,2) 400
set matrix(1,3) 600
set i 1; set j 2
set cell $matrix($i,$j)
puts $cell => 400

Ex 2 : set wwid(Davis,Mike) 10948292


set wwid(Smith,Jane) 18420392
puts $wwid(Davis,Mike) => 10948292

Note that spaces are significant here, set wwid(Davis, Mike) 10948292 passes three arguments
to the set command (wwid(Davis, Mike), 10948292), which will cause an error
ENV :

The env array is a built-in array whose elements are the environmental variables for the process
puts $env(USER) => mltravni

Command substitution:

EX : set a [set b Physical Design Engineering]


set len [string length $a]

Arithmetic :

The expr command is used to do arithmetic operations


Also note that there is a incr command that will increment a variable

EX : set var 4
incr var
puts $var => 5

precedence :

() Parentheses Evaluated first. If there are several pairs of parentheses


on the same level, they are evaluated left to right
*, / or % Multiplication Evaluated second. If there are several pairs of parentheses
on the same level, they are evaluated left to right

+ or - Addition Evaluated last. If there is more than one, the operators are
Subtraction evaluated from right to left.

Strings
A backslash can also be used to continue a long line on a another line

EX : set total_sum [expr [expr $value1 + $value2] + \


[expr [string length $variable3]]]

Grouping words with double quotes allows substitutions to occur (i.e. command substitutions,
variable substitutions, backslash substitutions)
Grouping words within curly braces disables substitutions

EX : set site1 Folsom


set site2 Chandler
puts $site1 $site2" => Folsom Chandler
puts {$site1 $site2} => $site1 $site2
puts "$site1 {$site2}" => Folsom {Chandler}
Format :

EX : set site1 Folsom


set site2 Chandler
puts $site1 $site2" => Folsom Chandler
puts {$site1 $site2} => $site1 $site2
puts "$site1 {$site2}" => Folsom {Chandler}

# Example of conversion specifier usage.

puts [format %f 455.954] => 455.954000


puts [format %f +455.34] => 455.340000
puts [format %d -455] => -455
puts [format %o 455] => 707

Field width :

EX : puts [format %5d 23] => 23


puts [format %5d 123] => 123
puts [format %5d 12345] => 12345
puts [format %5d 1234567] => 1234567

Precision :

EX : set string1 Hello there.


puts [format %.8s $string1] => Hello th
puts [format %5.2f 123.353] => 123.35

Rounding :

EX : set decimal 1243.532


set rounded [format "%.0f" $decimal]; # Round to zero decimal places.
puts $rounded => 1244
set decimal 1243.432
set rounded [format "%.0f" $decimal]; # Round to zero decimal places.
puts $rounded => 1243

The minus sign (-) flag will left justify output

EX : puts [format %+d %+d 500 -500] => +500 -500


puts [format %-5d 123] => 123
puts [format %-5d 12345] => 12345

String Length :

EX : puts length of \$var1 is: [string length $var1]


String Index :

EX : puts The 4th character of \$var1 is: [string index $var1 3]

String range :

EX : puts characters 3 through 5 of \$var1 are: [string range $var1 3 5]


puts last three characters of \$var1 are: [string range $var1 end-2 end]

string first :

To find the index of the first occurrence of a character use the string command with the first option. -1 is
returned if there is no match

EX : puts first occurrence of \a\ within \$var1 is at index: [string first a $var1]

string last :

To find the index of the last occurrence of a character use the string command with the last option

EX : puts last occurrence of \a\ within \$var1 is at index: [string last a $var1]

string match :

EX : if {[string match *\.tcl $filename]} {


puts $filename is a tcl script
}

if {[string match {[a-zA-Z0-9]} $var]} {


puts $var contains a single alphanumeric character
}
if {[string match {[a-zA-Z0-9]*} $var]} {
puts $var contains alphanumeric characters
}
String check :

For example, to test if something is an integer:


if {![string is integer strict $value]} {
puts Invalid input. Enter a number.
}
To test if something is a boolean:
if {[string is boolean $var]} {
puts $var is a boolean value
}
Other character classes
alnum any alphabet or digit character
alpha any alphabet character
boolean a boolean value (e.g. 0, 1, true, false)
digit any digit character
false a boolean false value (0, false)
integer an integer
lower a string of all lower case
space a space, tab, newline, carriage return, vertical tab, backspace
true a boolean true value (1, true)
upper a string of all upper case
wordchar a alphabet, digit or underscore character

String Compare :

Returns:
-1 if string1 is less than string2
0 if string1 is equal to string2
1 if string1 is greater than string2

EX : If {[string compare $word1 $word2] == 1} {


puts $word1 is greater than $word2
}

String equal :

Returns 1 if strings are equal, else 0

EX : set string1 McDonalds


set string2 mcdees

if {[string equal nocase length 3 $string1 $string2]} {


puts strings are equal
}

String lower/upper :

EX : puts [string tolower HELLO] => hello


puts [string toupper hello] => HELLO

string trim :

Returns string with all occurrences of trimChars removed from both ends

EX : puts [string trim abracadabra abr] => cad


puts [string trimleft abracadabra abr] => cadabra
puts [string trimright abracadabra abr] => abracad
puts [string totitle hello] => Hello
Control Structures
Operator Data Type Returns

< Numeric True when left operand is less than right.


> Numeric True when left operand is greater than right.
<= Numeric True when left is less than or equal to right.
>= Numeric True when left is greater than or equal to right.
== Numeric True when left operand is equal to right.
!= Numeric True when left operand is not equal to right.
eq String True when left operand is equal to right.
ne String True when left operand is not equal to right

If condition:

EX : if {$var == 1} {
puts The variable is 1.
} else {
puts The variable is not 1.
}

Nested if else :

EX : if {$variable == 2} {
puts The variable is 2.
} elseif {$variable == 1} {
puts The variable is 1.
} elseif {$variable == 0} {
puts The variable is 0.
} else {
puts The variable is not equal to 2, 1 or 0.
}
Switch :

EX : set number 1
switch $number {
0{
puts Match, number is equal to 0
}
1{
puts Match, number is equal to 1
}
default {
puts No matches
}
}
There are four flags that can be used with the switch statement:
-exact The value needs to match exactly one pattern (default behavior).
-glob Uses glob-style pattern matching.
-regexp Uses regular expression pattern matching.
-- No flag (or end of flags). Needed when the value might begin with -.

EX : - exact Example
switch exact -- $name {
PDE { set emp 200; puts The $name group has $emp employees }
CG { set emp 10000; puts The $name group has $emp employees. }
default { puts No match for switch statement.}
}
While :

EX : set number 0
while {$number < 100} {
puts $number is less than 100.
incr number
}

For :

EX : for { set index 0 } { $index <= 100 } { incr index 2 } {


puts Printing even numbers up to 100: $index.
}

Foreach :

EX : foreach element { one two three } {


puts $element
}

Break :

Immediately exits from the current loop (i.e. the innermost loop).

EX : set x 0
while { $x < 5 } {
incr x
if { $x == 3 } { break }
puts "$x"
}
=> 1
2
Condition :

EX : puts [expr ($x == 5)?" is 5":" is not 5"] => x is 5

catch :

The catch command can be used to trap errors


Syntax: catch command resultVariable

EX : if {[catch {string length $var1} result]} {


puts stderr $result
} else {
puts $var1 is $result characters long
}
If $var1 is undefined, then the catch command will catch the error and the script will continue
on without exiting. A message similar to the following would be outputted in this case:
can't read "var1": no such variable

Exit :

exit command will terminate the current script

EX : if {[catch {string length $var1} result]} {


puts stderr $result
exit
} else {
puts $var1 is $result characters long
}

Files

Open a file :

EX : set fileId [open file.txt r]

r # open for read access


r+ # open for read & write access, file must already exist
w # create for write access
w # create for write & read access, file can be new
a # open for append, file must already exist
a+ # open for append, file can be new

EX : if [catch { open file.txt r } fileId] {


puts stderr Could not open file.txt: $fileId
} else {
read from file
}
An error message would be something like:
Could not open file.txt: couldn't open "file.txt": no such file or directory

Closing file :

EX : if [catch { open file.txt r } fileId] {


puts stderr Could not open file.txt: $fileId
} else {
read from file
close $fileId
}

Read line :

EX : gets $fileId line ;# Read one line from filehandle, store in $line

The gets command returns a -1 when EOF occurs

Write to file :

EX : set FH [open file.txt a] ;# open file for edit


puts $FH Hello ;# print Hello to file
close $FH

Command ARGV :

The first command-line argument is stored in the $argv[0] variable, the second in $argv[1]

To loop over all command line arguments:


foreach arg $argv {
puts $arg ;# print command line args
}

The number of arguments to the script is stored in the argc variable.

The name of the script is stored in the argv0 variable

puts You passed $argc arguments to the $argv0 script

File Commands :

The file readable command returns 1 if the file is readable by the user, otherwise 0.

if { [file readable $filepath] } {


do stuff
}
The file writeable command returns 1 if the file is writable by the user, otherwise 0.

if { [file writeable $filepath] } {


do stuff
}

The file executable command returns 1 if the file is executable, otherwise 0.

if { [file executable $filepath] } {


do stuff
}

The file owned command returns 1 if the file is owned by the user, otherwise 0.

if { [file owned $filepath] && [file writable $filepath] } {


do stuff
}

The file exists command returns 1 if the file exists and the user has search access in all the
directories leading to the file, otherwise 0.

if { [file exists $filepath] && [file readable $filepath] } {


do stuff
}
The file size command returns the size of a file in bytes.

set size [file size $filepath]

The file isdirectory command returns 1 if the entry is a directory, otherwise 0.

if { [file isdirectory $dirpath] } {


do stuff
}

The file isfile command returns 1 if the entry is a file, otherwise 0.

if { [file isfile $dirpath] && [file writable $filepath] } {


do stuff
}

The file dirname command will return the directory portion of a path.
If the path contains no slashes, then . is returned.
set filepath /extra1/mltravni/apr_green_go_button.tcl
set dirpath [file dirname $filepath]
puts $dirpath => /extra1/mltravni
The file extension command will return the filename extension

set filepath /extra1/mltravni/apr_green_go_button.tcl


set ext [file extension $filepath]
puts $ext => tcl

The file rootname command will return the filename without the extension

set filepath /extra1/mltravni/apr_green_go_button.tcl


set rootName [file rootname $filepath]
puts $rootName => /extra1/mltravni/apr_green_go_button

The file tail command will return the filename without the directory
Returns all of the characters in the filename after the last slash

set filepath /extra1/mltravni/apr_green_go_button.tcl


set tailName [file tail $filepath]
puts $tailName => apr_green_go_button.tcl

The file type command returns the type of the file


The return value is a string:
file
directory
characterSpecial ;# character oriented device
blockSpecial ;# block oriented device
fifo ;# pipe
link ;# symbolic link
socket

Ex : set fileType [file type ~/.alias]


puts $fileType => file

The file readlink command returns the name of the file (full path) pointed to by a symbolic link.
If the file is not a link or cant be read then an error is returned

set linkpath [file readlink $linkedFile]


puts $linkpath

The file atime command returns the time the file was last accessed
Returns the number of seconds since 1/1/1970

Generates an error if the file doesn't exist, or the access time cannot be queried
set lastAccess [file atime $file]

The file mtime command returns the time the files was last modified
Returns the number of seconds since 1/1/1970.
set lastMod [file mtime $file]
The file copy command copies a file.
The source and destinations can be directories.
.
Ex: file copy force $file1 $file2 $file3 $destination
file copy .alias .alias_bckup

The file delete command deletes a file


The force switch must be used to delete a non-empty directory

Ex : file delete .alias_bckup

The file mkdir command creates one or more new directories

Ex : file mkdir $dir1 $dir2 $dir3

The file rename command renames a file or directory


The force switch allows you to overwrite an existing file

Ex : file rename force $oldName $newNam

The file split command splits a path into its pathname components

Ex : set splitPath [file split /usr/users/mltravni]


puts $splitPath => / usr users mltravni

The file join command joins pathname components into a new pathname
Use join to construct file names.
Syntax: file join name ?name ?

Ex : set joinPath [file join /usr/users/mltravni/ scripts/tcl/ fixDRCs.tcl]


puts $joinPath => /usr/users/mltravni/scripts/tcl/fixDRCs.tcl

Glob :

The glob command can be used to retrieve a set of filenames in a directory.


Always use the ncomplain switch otherwise Tcl will return an error if glob returns an empty list.
The glob function returns a list of all names that match a specified pattern.

Ex : set tcl_files [glob nocomplain *.tcl] ;# Grab all .tcl files in current directory

Regular Expressions

Syntax : regexp error $var

Tcl provides several special escape characters for use in regular expressions.
\d match a digit character (0-9)
\D match a non-digit character
\s match a white-space character
\S match a nonwhite-space character
\w match a letter, digit or underscore
\W match a non-letter/digit/underscore
. match any character
? match zero or one times
* match zero or more times
+ match one or more times
{n} match n times
{n,} match at least n times
{n,m} match between n & m times (inclusive)
^ match the beginning of the string
$ match the end of the string

Check Length Of Lines


Ex : gets stdin line
If { [regexp { .{10,}} $line] } {
puts Type shorter lines!
}
set str Cost: \$40,999.95
if { [regexp {(?x)
\$ # match a dollar sign
\d+ # match one or more digits
,? # match zero or one comma
\d* # match zero or more digits
\.? # match zero or one periods
\d* # match zero or more digits
} $str] } {
puts Matches
} else {
puts Does not match
}

More Examples

{(abc)+} ;# match: abc, abcabc, abcabcabc


{^(x|y)} ;# match either x or y at beginning of a line
{(a|b)(c|d)} ;# match: ac, ad, bc, or bd
{^(yes|Yes|YES)$} ;# match: yes, Yes, or YES

Ex : set text Hello


if { [regexp {[^aeiou]} $text] } { ;# match any single non-vowel
puts There are consonants
}
Store Matches:

regexp error $var matchVar

Pattern substitution:

Ex: set text Hello PDE.


regsub PDE $text CG newText
puts $newText => Hello CG

The all option means to replace all occurrences of a pattern, otherwise only the first
occurrence is replaced

regsub all e $var w newVar

The nocase option is used to ignore casing.Basically any uppercase characters in the string are
converted to lower-case during the matching process

regsub nocase error $var warning newVar

Use the -- option if your pattern potentially starts with a dash character.
The -- option basically signals the end of the options and allows patterns to begin with a dash

regsub nocase -- 50 $alphanum 100 newAlphanum

Procedures

proc <procedure_name> {?arguments?} {


. statements .
}
Upvar :

Ex : proc scale {xvalue yvalue scalefactor} {


upvar $xvalue x
upvar $yvalue y
set x [expr $x * $scalefactor]
set y [expr $y * $scalefactor]
}
set x 5; set y 10;
scale x y 2
puts "After scaling x=$x, y=$y" => After scaling x=10, y=20
The upvar command causes x to become a reference to $xvalue, and y to become a
reference to $yvalue.
A reference is a variable that points to another value in memory (i.e. points to another
variable)

Você também pode gostar