TCL - Tool Command Language
TCL - Tool Command Language
LANGUAGE
TCL OverView:
• Tcl is a general purpose multi-paradigm system programming language. It is a scripting
language that aims at providing the ability for applications to communicate with each other.
On the other hand, Tk is a cross platform widget toolkit used for building GUI in many
languages.
• Tcl is shortened form of Tool Command Language. John Ousterhout of the University of
California, Berkeley, designed it.
• It is a combination of a scripting language and its own interpreter that gets embedded to the
application, we develop with it.
• Tcl was developed initially for Unix. It was then ported to Windows, DOS, OS/2, and Mac
OSX. Tcl is much similar to other unix shell languages like Bourne Shell (Sh), the C Shell
(csh), the Korn Shell (sh), and Perl.
• It aims at providing ability for programs to interact with other programs and also for acting as
an embeddable interpreter. Even though, the original aim was to enable programs to interact,
you can find full-fledged applications written in Tcl/Tk.
Features of TCL:
•Reduced development time.
•Write once, run anywhere. It runs on Windows, Mac OS X, and almost on every Unix
platform.
•Quite easy to get started for experienced programmers; since, the language is so simple that
they can learn Tcl in a few hours or days.
•You can easily extend existing applications with Tcl. Also, it is possible to include Tcl in C,
C++, or Java to Tcl or vice versa.
•Finally, it's an open source, free, and can be used for commercial applications without any
limit.
Applications :
Tcl is a general-purpose language and you can find Tcl everywhere. It includes,
Text Editor:
• This will be used to type your program. Examples of a few text editors include Windows
Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
• The files you create with your text editor are called source files and contain program source
code. The source files for Tcl programs are named with the extension ".tcl".
The Tcl Interpreter:
It is just a small program that enables you to type Tcl commands and have them executed line by
line. It stops execution of a tcl file, in case, it encounters an error unlike a compiler that executes
fully.
#!/usr/bin/tclsh
puts "Hello World!“
Basic Syntax:
RUN using “$tclsh test.tcl”
#!/usr/bin/tclsh OUTPUT:
In Tcl, we use new line or semicolon to terminate the previous line of code. But
semicolon is not necessary, if you are using newline for each command.
Comments:
Comments are like helping text in your Tcl program and the interpreter
ignores them. Comments can be written using a hash_(#) sign in the
beginning. Output:
#!/usr/bin/tclsh
# my first program in Tcl
puts "Hello World!"
Multiline or block comment is written using 'if' with condition '0'. An example is
shown below.
#!/usr/bin/tclsh
if 0 {
my first program in Tcl program Its very simple
}
puts "Hello World!"
Inline comments use ;#. An example is given below.
#!/usr/bin/tclsh
puts "Hello World!" ;# my first print in Tcl program
Output:
IDENTIFIERS:
• A Tcl identifier is a name used to identify a variable, function, or any other user-
defined item.
• An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores, dollars ($) , and digits (0 to 9).
• Tcl does not allow punctuation characters such as @, and % within identifiers.
• Tcl is a case sensitive_ language.
• For example, input1 and Input1 are different identifiers.
• Examples:
zara abc move_name a_123
myname50 _temp j a23b9 retVal
WhiteSpaces:
• Whitespace is the term used in Tcl to describe blanks, tabs, newline characters,
and comments.
• Whitespace separates one part of a statement from another and enables the
interpreter to identify where one element in a statement, such as puts, ends
and the next element begins. Therefore, in the following statement −
#!/usr/bin/tclsh
env
4. Used for representing the array of elements that are environmental
variables
5. errorCode
Provides the error code for last Tcl error.
6. errorInfo
Provides the stack trace for last Tcl error.
7. tcl_library
Used for setting the location of standard Tcl libraries.
Sr.No Special Variable & Description
tcl_pkgPath
8. Provides the list of directories where packages are generally installed.
9. tcl_patchLevel
Refers to the current patch level of the Tcl interpreter.
tcl_precision
10. Refers to the precision i.e. number of digits to retain when converting to
floating-point numbers to strings. The default value is 12.
tcl_version
11. Returns the current version of the Tcl interpreter.
TCL Commands:
• Tcl is a Tool command language, commands are the most vital part
of the language.
• Tcl commands are built in-to the language with each having its own
predefined function.
• These commands form the reserved words of the language and
cannot be used for other variable naming.
• Tcl command is actually a list of words, with the first word
representing the command to be executed. The next words
represent the arguments
• In order to group the words into a single argument, we enclose
multiple words with "" or {}.
#!/usr/bin/tclsh
puts stdout "Hello, world!"
In the above code, ‘puts’ is the Tcl command, ‘stdout’ is argument1, and "Hello World" is
argument2.
Here, stdout makes the program to print in the standard output device
Command Substitution
In command substitutions, square brackets are used to evaluate the scripts inside
the square brackets.
#!/usr/bin/tclsh
puts [expr 1 + 6 + 9]
Variable Substitution
In variable substitutions, $ is used before the variable name and this returns the
contents of the variable.
#!/usr/bin/tclsh
set a 3
puts $a
Backslash Substitution
These are commonly called escape sequences; with each backslash, followed by a
letter having its own meaning.
#!/usr/bin/tclsh
puts "Hello\nWorld"
The above statement will create a variable name myVariable and stores it as a string
even though, we have not used double quotations. Now, if we try to make an arithmetic
on the variable, it is automatically turned to an integer.
#!/usr/bin/tclsh
set myVariable 18
puts [expr $myVariable + 6 + 9]
String Representations
In Tcl, you need not include double quotes when it's only a single word
#!/usr/bin/tclsh
set myVariable hello
puts $myVariable
#!/usr/bin/tclsh
set myVariable "hello world“
puts $myVariable
set myVariable {hello world}
puts $myVariable
List:
• List is nothing but a group of elements.
• A group of words either using double quotes or curly braces can be used to
represent a simple list.
• A simple list is shown below −
#!/usr/bin/tclsh
set myVariable {red green blue}
puts [lindex $myVariable 2]
set myVariable "red green blue"
puts [lindex $myVariable 1]
Associative Array:
• Associative arrays have an index (key) that is not necessarily an integer.
• It is generally a string that acts like key value pairs.
• A simple example is shown below −
#!/usr/bin/tclsh
set marks(english) 80
puts $marks(english)
set marks(mathematics) 90
puts $marks(mathematics)
Handles:
Tcl handles are commonly used to represent files and graphics objects. These can include
handles to network requests and also other channels like serial port communication,
sockets, or I/O devices.
• The set command is used for assigning value to a variable. The syntax for set command is,
• set variableName value
Dynamic Typing
• Tcl is a dynamically typed language.
• The value of the variable can be dynamically converted to the required type
when required
#!/usr/bin/tclsh
set variableA "10“
puts $variableA
set sum [expr $variableA +20];
puts $sum
Mathematical Expressions
• expr is used for representing mathematical expression.
• The default precision of Tcl is 12 digits. In order to get floating point results, we should
add at least a single decimal digit.
#!/usr/bin/tclsh
set variableA "10"
set result [expr $variableA / 9];
puts $result
set result [expr $variableA / 9.0];
puts $result
set variableA "10.0"
set result [expr $variableA / 9];
puts $result
you can change the precision by using tcl_precision special variable. It is
shown below
#!/usr/bin/tclsh
set variableA "10"
set tcl_precision 5
set result [expr $variableA / 9.0];
puts $result
Tcl - Operators
• An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations.
• Tcl language is rich in built-in operators and provides the following types of
operators −
•Arithmetic Operators
•Relational Operators
•Logical Operators
•Bitwise Operators
•Ternary Operator
Arithmetic Operators
Assume variable ‘A’ holds 10 and variable ‘B’ holds 20, then −
&& Called Logical AND operator. If both the operands are non- (A && B) is false
zero, then condition becomes true.
|| Called Logical OR Operator. If any of the two operands is non- (A || B) is true.
zero, then condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical state
of its operand. If a condition is true then Logical NOT operator
will make false
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows −
(A | B) will give
Binary OR Operator copies a bit if it exists in either
| 61, which is 0011
operand.
1101
(A ^ B) will give
Binary XOR Operator copies the bit if it is set in one
^ 49, which is 0011
operand but not both.
0001
Binary Left Shift Operator. The left operands value is A << 2 will give
<< moved left by the number of bits specified by the right 240, which is
operand. 1111 0000
Binary Right Shift Operator. The left operands value is A >> 2 will give
>> moved right by the number of bits specified by the right 15, which is 0000
operand. 1111
Ternary Operator
• Tcl language uses the expr command internally and hence it’s not required for us
to use expr statement explicitly
Tcl - If Statement
An if statement consists of a Boolean expression followed by one or more
statements.
Syntax
The syntax of an 'if' statement in Tcl language is −
if {boolean_expression} {
# statement(s) will execute if the Boolean expression
is true
•} Tcl language uses the expr command internally and hence it's not required
for us to use expr statement explicitly.
#!/usr/bin/tclsh
set a 10
#check the boolean condition using if statement
if { $a < 20 } {
# if condition is true then print the following
puts "a is less than 20"
}
puts "value of a is : $a"
Tcl - If else Statement
• An if statement can be followed by an optional else statement, which executes
when the Boolean expression is false.
Syntax:
if {boolean_expression 1} {
# Executes when the boolean expression 1 is true
} elseif {boolean_expression 2} {
# Executes when the boolean expression 2 is true
} elseif {boolean_expression 3} {
# Executes when the boolean expression 3 is true
} else {
# executes when the none of the above condition is true }
#!/usr/bin/tclsh
set a 100
#check the boolean condition
if {$a < 20 } {
#if condition is true then print the following
puts "a is less than 20"
} else {
#if condition is false then print the following
puts "a is not less than 20"
}
puts "value of a is : $a"
Tcl - Nested If Statement
It is always legal in Tcl to nest if-else statements, which means you can use one if or else if statement
inside another if or else if statement(s).
Syntax
matchStringn {
bodyn
}
}
}
matchString2 {
body2
}
...
matchStringn {
bodyn
}
}
#!/usr/bin/tclsh
set a 100
set b 200
switch $a {
100 {
puts "This is part of outer
switch" switch $b {
200 {
puts "This is part of inner
switch!"
}
}
}
}
puts "Exact value of a is : $a"
puts "Exact value of a is : $b"
The ? : Operator
Tcl - Loops
A loop statement allows us to execute a statement or group of statements multiple times
and following is the general form of a loop statement in most of the programming
languages −
Tcl - While Loop
A while loop statement in Tcl language repeatedly executes a target statement
as long as a given condition is true.
Syntax:
The syntax of a while loop in Tcl language is −
while {condition} {
statement(s)
}
#!/usr/bin/tclsh
set a 10
#while loop execution
while { $a < 20 } {
puts "value of a: $a"
incr a
}
Tcl - For Loops
A for loop is a repetition control structure that allows you to efficiently write a code that
needs to be executed for a specific number of times
Syntax:
#!/usr/bin/tclsh
set languages(0) Tcl
set languages(1) "C Language"
puts $languages(0)
puts $languages(1)
Size of Array
The syntax for calculating size array is shown below.
[array size variablename]
#!/usr/bin/tclsh
set languages(0) Tcl
set languages(1) "C Language"
puts [array size languages]
Array Iteration
#!/usr/bin/tclsh
set languages(0) Tcl
set languages(1) "C Language"
for { set index 0 } { $index < [array size languages] } { incr index }
{
puts "languages($index) : $languages($index)" }
Indices of Array
The syntax for retrieving indices of array is shown below.
#!/usr/bin/tclsh
set personA(Name) "Dave"
set personA(Age) 14
puts [array names personA]
Iteration of Associative Array
#!/usr/bin/tclsh
set personA(Name) "Dave"
set personA(Age) 14
foreach index [array names personA] {
puts "personA($index): $personA($index)" }
Tcl - Strings
Escape
Meaning
sequence
\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
#!/usr/bin/tclsh
puts "Hello\tWorld\n\nwelcome\t\”TCL SCRIPTING\”";
String Command
Sr.No. Methods & Description
compare string1 string2
1 Compares string1 and string2 lexographically. Returns 0 if equal, -1 if string1 comes
before string2, else 1.
5 length string
Returns the length of string.
8 tolower string
Returns the lowercase string.
9 toupper string
Returns the uppercase string.
#!/usr/bin/tclsh
set s1 "Hello"
set s2 "World"
set s3 "World"
puts [string compare $s1 $s2]
if {[string compare $s2 $s3] == 0} {
puts "String \'s1\' and \'s2\' are same.";
}
if {[string compare $s1 $s2] == -1} {
puts "String \'s1\' comes before \'s2\'.";
}
if {[string compare $s2 $s1] == 1} {
puts "String \'s2\' comes after \'s1\'.";
}
Index of String
#!/usr/bin/tclsh
set s1 "Hello World"
set s2 "o"
puts "First occurrence of $s2 in s1"
puts [string first $s2 $s1]
puts "Character at index 0 in s1"
puts [string index $s1 0]
puts "Last occurrence of $s2 in s1"
puts [string last $s2 $s1]
puts "Word end index in s1"
puts [string wordend $s1 20]
puts "Word start index in s1"
puts [string wordstart $s1 20]
Length of String
#!/usr/bin/tclsh
set s1 "Hello World"
puts "Length of string s1"
puts [string length $s1]
Handling Cases
#!/usr/bin/tclsh
set s1 "Hello World"
puts "Uppercase string of s1“
puts [string toupper $s1]
puts "Lowercase string of s1"
puts [string tolower $s1]
Trimming Characters
#!/usr/bin/tclsh
set s1 "Hello World"
set s2 "World"
puts "Trim right $s2 in $s1"
puts [string trimright $s1 $s2]
set s2 "Hello"
puts "Trim left $s2 in $s1"
puts [string trimleft $s1 $s2]
set s1 " Hello World "
set s2 " "
puts "Trim characters s1 on both sides of s2"
puts [string trim $s1 $s2]
Matching Strings
#!/usr/bin/tclsh
set s1 "[email protected]"
set s2 "*@*.com"
puts "Matching pattern s2 in s1"
puts [string match "*@*.com" $s1 ]
puts "Matching pattern tcl in s1"
puts [string match {tcl} $s1]
Append Command
#!/usr/bin/tclsh
set s1 "Hello"
append s1 " World"
puts $s1
Format command
Specifier Use
%s String representation
%d Integer representation
%f Floating point representation
%e Floating point representation with mantissa-exponent form
%x Hexa decimal representation
#!/usr/bin/tclsh
puts [format "%f" 43.5]
puts [format "%e" 43.5]
puts [format "%d %s" 4 tuts]
puts [format "%s" "Tcl Language"]
puts [format "%x" 40]
Scan command
Scan command is used for parsing a string based to the format specifier.
#!/usr/bin/tclsh
puts [scan "90" {%[0-9]} m]
puts [scan "abc" {%[a-z]} m]
puts [scan "abc" {%[A-Z]} m]
puts [scan "ABC" {%[A-Z]} m]
Tcl – Lists:
Creating a List
The general syntax for list is given below −
Length of List
The syntax for length of list is given below −
llength listName
#!/usr/bin/tclsh
set var {orange blue red green}
puts [llength $var]
List Item at Index
#!/usr/bin/tclsh
set var {orange blue red green}
set var [lreplace $var 2 3 black white]
puts $var
#!/usr/bin/tclsh
set colours [dict create colour1 "black" colour2 "white"]
puts [dict size $colours]
Value for Key in Dict
The syntax for retrieving value for key in dict is shown below
#!/usr/bin/tclsh
set colours [dict create colour1 "black" colour2 "white"]
set value [dict get $colours colour1]
puts $value
All Keys in Dict
The syntax for retrieving all keys in dict is shown below −
[dict keys $dictname]
#!/usr/bin/tclsh
set colours [dict create colour1 "black" colour2 "white"]
set keys [dict keys $colours]
puts $keys
All Values in Dict
The syntax for retrieving all values in dict is shown below −
#!/usr/bin/tclsh
set colours [dict create colour1 "black" colour2 "white"]
foreach item [dict keys $colours] {
set value [dict get $colours $item]
puts $value }
Key Exists in Dict
The syntax for checking if a key exists in dict is shown below −
#!/usr/bin/tclsh
#!/usr/bin/tclsh
proc add {a b} {
return [expr $a+$b]
}
puts [add 10 30]
Procedures with Variable Arguments
#!/usr/bin/tclsh
#!/usr/bin/tclsh
proc add {a {b 100} } {
return [expr $a+$b]
}
puts [add 10 30]
puts [add 10]
Recursive Procedures
#!/usr/bin/tclsh
proc factorial {number} {
if {$number <= 1} {
return 1
}
return [expr $number * [factorial [expr $number - 1]]]
}
puts [factorial 3]
puts [factorial 5]
FILE – I/O
• Tcl supports file handling with the help of the built in commands open, read, puts,
gets, and close.
• A file represents a sequence of bytes, does not matter if it is a text file or binary file.
Opening Files:
• Tcl uses the open command to open files in Tcl.
• The syntax for opening a file is as follows −
w
2 Opens a text file for writing, if it does not exist, then a new file is created else existing file is
truncated.
a
3 Opens a text file for writing in appending mode and file must exist. Program will start appending
content in the existing file content.
4 r+
Opens a text file for reading and writing both. File must exist already.
w+
5 Opens a text file for reading and writing both. It first truncate the file to zero length if it exists
otherwise create the file if it does not exist.
a+
6 Opens a text file for reading and writing both. It creates the file if it does not exist. The reading
will start from the beginning, but writing can only be appended.
Closing a File
• To close a file, use the close command.
• The syntax for close is as follows −
close fileName
• Any file that has been opened by a program must be closed when the
program finishes using that file.
• In most cases, the files need not be closed explicitly; they are closed
automatically when File objects are terminated automatically.
Writing a File
• Puts command is used to write to an open file.
#!/usr/bin/tclsh
set fp [open "input.txt" w+]
puts $fp "test"
close $fp
• When the above code is compiled and executed, it creates a new file input.txt in the
directory that it has been started under
Reading a File
• The simple command to read from a file
#!/usr/bin/tclsh
set fp [open "input.txt" w+]
puts $fp "test“
close $fp
set fp [open "input.txt" r]
set file_data [read $fp]
puts $file_data
close $fp
another example for reading file till end of file line by line −
#!/usr/bin/tclsh
set fp [open "input.txt" w+]
puts $fp "test\ntest"
close $fp
set fp [open "input.txt" r]
while { [gets $fp data] >= 0 }
{ puts $data
}
close $fp
Tcl - Error Handling
• Error handling in Tcl is provided with the help of error and catch commands.
Error syntax
error message info code
In the above error command syntax,
• message is the error message,
• info is set in the global variable errorInfo and
• code is set in the global variable errorCode.
Catch Syntax
catch script resultVarName
In the above catch command syntax,
• script is the code to be executed,
• resultVarName is variable that holds the error or the result.
• The catch command returns 0 if there is no error, and 1 if there is an error.
#!/usr/bin/tclsh
proc Div {a b} {
if {$b == 0} {
error "Error generated by error" "Info String for error"
401
} else {
return [expr $a/$b]
}
}
if {[catch {puts "Result = [Div 10 0]"} errmsg]} {
puts "ErrorMsg: $errmsg"
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"
}
if {[catch {puts "Result = [Div 10 2]"} errmsg]} {
puts "ErrorMsg: $errmsg“
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"
}
#!/usr/bin/tclsh
catch {set file [open myNonexistingfile.txt]} result
puts "ErrorMsg: $result"
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"
Tcl - Built-in Functions
Tcl provides a number of built-in functions (procedures) for various operations. This
includes −
•Functions for list handling.
1 abs arg
Calculates the absolute value of arg.
2 acos arg
Calculates the arccosine of arg.
3 asin arg
Calculates the arcsine of arg.
4 atan arg
Calculates the arctangent of arg.
5 atan2 y x
Calculates the arctangent of the quotient of its arguments(y/x).
6 ceil arg
Calculates the smallest integer greater than or equal to a number.
7 cos arg
Calculates the cosine of arg.
Sr.No. Method & Description
8 cosh arg
Calculates the hyperbolic cosine of arg.
double arg
9 Calculates if arg is a floating-point value, returns arg, otherwise converts arg to
floating-point and returns the converted value.
10 exp arg
Calculates an exponential function (e raised to the power of arg).
11 floor arg
Calculates the largest integer less than or equal to arg.
fmod x y
12 Calculates the floating-point remainder of the division of x by y. If y is 0, an error is
returned.
13 hypot x y
Calculates the length of the hypotenuse of a right-angled triangle sqrt(x*x+y*y).
int arg
14 Calculates if arg is an integer value of the same width as the machine word, returns
arg, otherwise converts arg to an integer.
Sr.No. Method & Description
15 log arg
Calculates the natural logarithm of arg.
16 log10 arg
Calculates the base 10 logarithm of arg.
pow x y
17 Calculates the value of x raised to the power y. If x is negative, y must be an integer
value.
18 rand
Calculates a pseudo-random number between 0 and 1.
19 round arg
Calculates the value of arg rounded to the nearest integer.
20 sin arg
Calculates the sine of arg.
21 sinh arg
Calculates the hyperbolic sine of arg.
Sr.No. Method & Description
21 sinh arg
Calculates the hyperbolic sine of arg.
22 sqrt arg
Calculates the square root of arg. arg must be positive.
srand arg
23 Calculates a pseudo-random number between 0 and 1. The arg, which must be an integer, is used
to reset the seed for the random number generator of rand.
24 tan arg
Calculates the tangent of arg.
25 tanh arg
Calculates the hyperbolic tangent of arg.
wide arg
26 Calculates integer value at least 64-bits wide (by sign-extension if arg is a 32-bit number) for arg if
it is not one already.
#!/usr/bin/tclsh
namespace import ::tcl::mathfunc::*
puts [tan 10]
puts [pow 10 2]
puts [ceil 10.34]
puts [hypot 10 20]
puts [srand 45]
puts [log 10]
System Functions
The important system functions in Tcl includes,
1 %a
Day in short form, eg:Sun.
2 %A
Day in full form eg:Sunday.
3 %b
Month in short form.
4 %B
Month in full form.
5 %d
Day of month.
6 %j
Julian day of year.
7 %m
Month in number.
Sr.No. Format & Description
8 %y
Year in two digits.
9 %Y
Year in four digits.
10 %H
Hour in 24 hour clock.
11 %I
Hour in 12 hour clock.
12 %M
Minutes.
13 %S
Seconds.
14 %p
AM or PM.
Sr.No. Format & Description
15 %D
Date in number, mm /dd/yy.
16 %r
Time in 12 hour clock.
17 %R
Time in 24 hour clock without seconds.
18 %T
Time in 24 hour clock with seconds.
%Z
19 Time Zone Name like GMT, IST, EST and so
on.
REGULAR EXPRESSIONS
• The "regexp" command is used to match a regular expression in Tcl.
• A regular expression is a sequence of characters that contains a search pattern.
• It consists of multiple rules.
Sr.No. Rule & Description
x
1
Exact match.
[a-z]
2
Any lowercase letter from a-z.
.
3
Any character.
^
4
Beginning string should match.
$
5
Ending string should match.
Sr.No. Rule & Description
\^
6 Backlash sequence to match special character
^.Similarly you can use for other characters.
()
7 Add the above sequences inside parenthesis to make a
regular expression.
x*
8 Should match 0 or more occurrences of the preceding
x.
x+
9 Should match 1 or more occurrences of the preceding
x.
[a-z]?
10
Should match 0 or 1 occurrence of the preceding x.
Sr.No. Rule & Description
{digit}
11 Matches exactly digit occurrences of previous
regex expression. Digit that contains 0-9.
| -Alternative
12
Must match one alternative
{digit1,digit2}
Occurrences matches the range between digit1
13
and digit2 occurrences of previous regex
expression.
Syntax
The syntax for regex is given below −
• Full match is any variable to hold the result of matched regex result.
• Submatch1 to SubMatchn are optional subMatch variable that holds the result of sub match
patterns.
#!/usr/bin/tclsh
regexp {([A-Za-z]*)} "Tcl Tutorial" a b
puts "Full Match: $a"
puts "Sub Match1: $b"
Multiple Patterns:
• This is example pattern for any alphabets followed by any character followed by
any alphabets.
#!/usr/bin/tclsh
regexp {([A-Za-z]*).([A-Za-z]*)} "Tcl Tutorial" a b c
puts "Full Match: $a"
puts "Sub Match1: $b“
puts "Sub Match2: $c"
Switches for Regex Command
The list of switches available in Tcl are,
•nocase − Used to ignore case.
•indices − Store location of matched sub patterns instead of matched characters.
•line − New line sensitive matching. Ignores the characters after newline.
•start index − Sets the offset of start of search pattern.
•Marks the end of switches
#!/usr/bin/tclsh
regexp -nocase {([A-Z]*.([A-Z]*))} "Tcl Tutorial" a b c
puts "Full Match: $a"
puts "Sub Match1: $b“
puts "Sub Match2: $c"
#!/usr/bin/tclsh