Presentation is loading. Please wait.

Presentation is loading. Please wait.

TCL Training Joshi Sravan Kumar K 21-Nov-2011.

Similar presentations


Presentation on theme: "TCL Training Joshi Sravan Kumar K 21-Nov-2011."— Presentation transcript:

1 TCL Training Joshi Sravan Kumar K 21-Nov-2011

2 Introduction TCL ( Tool Command Language)
Designed by “John Ousterhout” in 1988 Every thing is a command Syntax: commandName <arg1> <arg2> …<argN> Command should end with a new line or semicolon (;) Every thing is represented as a String. Runs in a TCL interpreter. Interprets and runs the code line by line

3 TCL Command – set, puts set is the assignment command
Syntax: set <variableName> <variableValue> Example: set user root set pi 3.14 puts is the Text output Command Syntax : puts -nonewline channelId <text> * nonewline and channelId are optional * default channelId is STDOUT puts Hello

4 TCL Command – set, puts Variable name should be preceded with $ to access the variable defined using set command Example: set name Cisco puts “$name makes routers”; Any thing written after the literal pound (#) is assumed to be a comment. Any previous command should end before a comment starts. It means the comment should start in a new line or should be preceded with a semicolon. Examples: set x 10 # This is a valid TCL Comment puts “Value of x is $x” ; #This is a valid TCL Comment set y 10 # This is not a valid comment

5 Executing TCL TCL Shell: TCL Executable File: Way-1
Prompt# expect expect1.1> puts Hello Hello expect1.2> TCL Executable File: Way-1 Open a file, say test.tcl in an editor Input TCL Program Run “expect test.tcl” TCL Executable File: Way-2 Input the header “#!/usr/bin/expect” and input tcl program Run “./test.tcl”

6 TCL Command – set, puts Correct answer is d What is the output of
puts –nonewline Hello how are you Hello Hello how are you Shows Blank Doesn’t execute Correct answer is d Because puts has more arguments than what it should have

7 Grouping arguments with quotes (“”)
Multiple words should be grouped with quotes (“”) or braces ({}) to pass them as a single argument. Correct Syntax for the previous code is puts –nonewline “Hello how are you” Substitution happens before passing the arguments to command. But only single pass of substitution happens Example: set x 10 puts “The value of x is $x”; # Variable x will be substituted first before passing the string to puts logic

8 Grouping arguments with quotes (“”)
What is the output of following code set 1 “One dollar” set dollar 1 puts “50 rupees is $$dollar” 50 rupees is $1 50 rupees is One dollar 50 rupees is $$dollar Doesn’t execute Correct Answer is a Only one round of variable substitution happens

9 Grouping arguments with quotes (“”)
Does this code output what I expect? puts “50 rupees is $1” No, as the variable ‘1’ is not defined. Can be solved with backslash (\). Following code gives me correct output puts “50 rupees is \$1” Backslash (\) disables the substitution for immediate character. Same problem can be solved with braces ({}) as well. Will be explained in the next section. Pre-defined back slash characters have special meaning.

10 Grouping arguments with quotes (“”)
Pre-defined backslash (\) characters. (Some important ones) \n New Line \r Carriage Return \t Tab \0dd Octal Value -- d is a digit from 0-7 \uHHHH H is a hex digit 0-9,A-F,a-f. This represents a 16-bit Unicode character. \xHH Hex Value Backslash at the end of line replaces the new line with a blank space and assumes it as single line of text puts “Hello how\ are you” #Above code is treated as single line of text and outputs Hello how are you

11 Grouping arguments with braces ({})
What is the output of set x “abc” set y “$x” puts “\$x=\$y=$x” abc=abc=abc $x=abc=abc $x=$y=abc $x=$y=$x Correct answer is C

12 Grouping arguments with braces ({})
Text grouped with braces ({}) will not go for substitution. Text will be passed to the command as it is. Example: puts {50 rupees is $1} ;# This code gives me the expected output Backslash will be treated as a literal back slash character with no special meaning. Only substitution that is still valid in braces ({}) is backslash (\) at the end of line. It still has the same meaning. Text once grouped with quotes or braces then the braces or quotes inside will be treated as the normal characters without any special meaning.

13 Grouping arguments with braces ({})
What is the output of set capital “Bangalore” puts “Capital of {Karnataka is $capital}” Capital of Karnataka is $capital Capital of Karnataka is Bangalore Capital of {Karnataka is $capital} Capital of {Karnataka is Bangalore} Correct Answer is d Text once grouped with quotes or braces, any grouping character inside will be treated as a literal character.

14 Grouping arguments with braces ({})
What is the output of set x “abc” set y “\{$x}” puts “$y” \{abc} $x {abc} \{$x} Correct Answer is C

15 Grouping arguments with ([])
Text inside the square brackets ([]) will be treated as a command. TCL interpreter substitutes the content of square brackets with output of the command inside the square brackets. Example: set capital [set city “Bangalore”] puts “$capital is a city and capital of Karnataka” #Outputs – Bangalore is a city and capital of Karnataka Substitution can go for multiple rounds till all commands are evaluated Square bracket that is escaped (\) will be treated as a literal square bracket. Square brackets inside the braces ({}) will not go for substitution.

16 Grouping arguments What is the output of set x “abc” set y “[set z {$x}]” puts “$y” abc $x {abc} {$x} Correct Answer is b Command inside square brackets is evaluated as separate command out of the current command context. Command inside the square bracket is evaluated as a separate command even it is inside the quotes

17 Grouping arguments What is the output of set x “how are” set y {hello
you} puts $y hello how are you hello $x you how are you hello $x you

18 Grouping arguments What is the output of set x “abc”
set y “[set z “{$x}”]” puts “$y” abc $x {abc} Doesn’t execute Correct answer is C

19 Grouping arguments What is the output of set x “abc”
set y “\[set z {$x}]” puts “$y” [set z {abc}] $x {abc} [set z {$x}} Correct answer is a

20 Arithmetic Operations
What does the following code output set x “2” set y “3” puts “Sum of $x and $y is $x+$y” Sum of 2 and 3 is $x+$y Sum of 2 and 3 is 5 Sum of 2 and 3 is 2+3 Doesn’t execute Correct answer is C

21 Arithmetic Operations – expr, incr
expr is the command that does arithmetic operations String literals will be identified as respective type (int, float …etc) and the operator characters (+, -, / , * ..etc) will be identified as respective operators. Example: set x “2” set y “3” puts “Sum of $x and $y is [expr $x+$y]” #Outputs - Sum of 2 and 3 is 5 * Here expr is surrounded by square brackets as the expr command is part of an argument of puts expr does one more round of substitutions on its argument. So it is recommended to keep the expression inside braces ({})

22 Arithmetic Operations – expr, incr
Argument to expr consists operands, operators, parentheses and spaces. Operands can be integers (decimal, octal, hex), floating point numbers or strings. decimal – Normal number octal – Any number having digits 0-7 preceded by 0 hex – Any number having digits 0-F preceded by 0x floating point - Any ANSI-C compliant floating number. e.g., 2.1, 7E3 , .0001 Operators define the operation to be performed on the operands.

23 Arithmetic Operations – expr, incr
Valid operators. ( Some important ones) -, + , ~, ! Unary minus, Unary plus, bitwise NOT,(only for integers) logical NOT. For numerical values +, -, *, /, % Add, Subtract, Multiply, divide and reminder ** Exponentiation. For integer and float <, >, >=, <=,== -- Logical comparison: lesser, greater, greater or equal, lesser or equal, equal. Returns 0 for false and 1 for true. Applicable for numerical values and Strings eq, ne, in, ni String comparison: equal, not equal, String in a list, String not in a list. Only for Strings &&, || Logical AND , Logical OR. Only for integer and float Math functions: (Some important ones) abs, ceil, double, floor, int, max, min, rand, round, sqrt.

24 Arithmetic Operations – expr, incr
What does the following code output set number “3” puts “[expr {int($number+2/sqrt(4))}]” 2 2.5 Doesn’t execute Correct answer a

25 Arithmetic Operations – expr, incr
Which of the following operators is not applicable for String operands eq && >= == Correct answer is b

26 Arithmetic Operations – expr, incr
What is the output of set x 10 set userinput {[set x [expr $x+1]]} ; #User INPUT puts “[expr $userinput == $x] and \$x = $x” 0 and $x = 10 0 and $x = 11 1 and $x = 10 1 and $x = 11 Correct answer is b

27 Arithmetic Operations – expr, incr
What is the output of set x 10 set userinput {[set x [expr $x+1]]} ; #User INPUT puts “[expr {$userinput == $x}] and \$x = $x” 0 and $x = 10 0 and $x = 11 1 and $x = 10 1 and $x = 11 Correct answer is a

28 Arithmetic Operations – expr, incr
incr is a command used to increment a number Example: set x 10 incr x puts $x ;# Outputs 11 This is exactly equal to set x [expr {$x+1}] puts $x

29 Arithmetic Operations – Hands-on
Write a program in TCL to print the hypotenuse length of a triangle in decimal for a given height (h) and base (b) Formula : hypotenuse = √(h² + b²) Solution: set h 3 set b 4 set hyp “[expr int(sqrt(h*h + b*b))]” puts “Hypotenuse is $hyp”

30 Arithmetic Operations – Hands-on
Write a program to Formula: bonus = IPF * CPF * C.SAT * 5,00,000 * 8/100 Solution: set bonus “[expr IPF*CPF*CSAT*500000*8/100]” puts “Bonus: $bonus”

31 Conditional Commands– if, elseif, else
if command is used to implement conditional statements Syntax: if <expr1> then <body1> elseif <expr2> then <body2>…..else <bodyN> * then, elseif and else are optional Example: set x 10 if {$x == 10} { puts “$x is 10” } elseif { $x == 20} { puts “$x is 20 } else { puts “$x is some thing else” }

32 Conditional Commands– if, elseif, else
Expression after the word if is evaluated exactly as it is in expr command If command will do a second round of substitution of expression, body by it self. So it is recommended to surround them with braces ({}) If the expression evaluates to be “true” then the body executes other wise it will go to elseif or else. Following is the mapping to interpret the expression as true/false Result of Expression False True Numerical Value Any other String yes/no no yes String true/false false true

33 Conditional Commands– if, elseif, else
What is the output of following code set x 10 set y 20 if {$x != $y} { puts “\$x = \$y” } elseif { $x == 10 } { puts “\$x = 10” } $x = $y $x = 10 Shows Blank Correct Answer is a

34 Conditional Commands– if, elseif, else
What is the output of following code set x 10 set y x if “$$y == 10” { puts “\$\$y = 10” } elseif “$y == $x” { puts “\$y = \$x” } else { puts “\$\$y != 10” } $$y != 10 $y = $x $$y = 10 Doesn’t execute

35 Conditional Commands– if, elseif, else
What is the output of following code set a "hello"; set b "false"; set c "-1"; set d "0“ if { $c } { if { $b } { puts "1” } else { puts "2” } } elseif { $d } { if { $a } { puts "3” } } 1 2 3 Doesn’t execute Correct answer is b

36 Conditional Commands– if, elseif, else
What does this code output set x “hello”;set y “hallow” if { $x == $y } { puts “Equal” } elseif { $x > $y } { puts “Greater” } else { puts “Lesser” } Equal Greater Lesser Doesn’t execute

37 Conditional Commands - switch
switch command is more comfortable and readable if there are multiple elseif statements in an if command. Syntax: switch <string> <pattern1> <body1> <pattern2> <body2> switch <string> { <pattern1> <body1> <pattern2> <body2> } The pattern that exactly matches with the <string>, respective body will be executed. Match here is a string comparison. No substitution happens in patterns. Example: set x “HELLO” switch $x { HELLO { puts “Match”} hello { puts “No match”} default { puts “Matches if nothing else matches”} }

38 Conditional Commands - switch
Using switch Using if set x “HELLO” switch $x { HELLO { puts “Match”} hello { puts “No match”} default { puts “Nothing matches”} } if { $x == “HELLO” } { puts “Match” } else if { $x == “hello” } { puts “No Match” } else { puts “Nothing matches”

39 Conditional Commands - switch
What is the output of following code set x 1 switch $x { 1.0 { puts “Match 1.0 } 1 { puts “Match 1” } ONE { puts “Match ONE” } default { puts “Match NONE” } } Match 1.0 Match 1 Match ONE Match NONE Correct Answer is b

40 Conditional Commands - switch
What is the output of following code set x ONE set y ONE switch $x { $y { puts “Match \$y” } 1 { puts “Match 1” } ONE { puts “Match ONE” } default { puts “Match NONE” } } Match $y Match 1 Match ONE Match NONE Correct Answer is c

41 Assignment – Session 1 Billing system of a super market.
Given an item name and quantity, our program should give the bill amount taking the following table as reference. Any total amount of above 2000 will attract 5% discount, above 5000 – 10 % and above – 15 % Input is in the form set item “fruits”; set quantity “10” Output should be Your total amount is : $<amount> Item Cost per Unit VAT % Pulses $ 50 4 % Fruits $ 100 4% Books $ 500 12.5 %

42 Looping Commands - while
while command is used to loop through set of commands again and again if certain criteria is met Syntax: while <test> <body> Similar to if command if <test> is evaluated to “true” then the <body> will be executed. After body is executed <test> will be evaluated again and <body> will be executed again .. and so on. Example: set i 1 while { $i < 10 } { puts “Value of i is $i” incr i }

43 Looping Commands - while
Similar to if command while will do a second round of substitution in the <test>. So it is recommended to surround <test> with braces. break statement can be used inside <body> to come out of the loop. continue statement can be used inside <body> to stop the body execution and re-evaluate the <test> Example: 1 set i 1 2 while { $i < 10 } { 3 incr i 4 if { $i > 7 } break; # if i > 7 goes to line number 8 5 if { $i < 5 } continue; # if i < 5 goes to line number 2 6 puts “Value of i is $i” 7 } 8 puts “Out of the loop. Value of i is $i”

44 Looping Commands - for for command does the same purpose as while command but with a different syntax to improve the readability Syntax: for <init>  <test> <next>  <body> <init> - Contains initialization section. Can contain any code or blank <test> - Test expression as in while and if. Shouldn’t be blank <next> - Normally contains increment command. Can contain any code or blank Example: for {set i 0} { $i < 10 } { incr i } { puts “Value of i is $i” }

45 Looping Commands – while Vs. for
Initialization Initialization Using while Using for set i 0 while { $i < 10 } { incr i if { $i > 7 } break if { $i < 5 } continue puts “Value of i is $i” } for {set i 0} { $i < 10 } { incr i } { Test Expression Next/Increment

46 Looping Commands What is the output of set i 10 while { $i < 50 } {
incr i if { $i >= 35 } break if { $i < 20 } continue puts –nonewline “$i “ } ….. 35 ….. 34 ….. 34 Infinite loop Correct Answer is b

47 Looping Commands What is the output of set i 10 while { $i < 50 } {
if { $i > 35 } break if { $i <= 20 } continue puts –nonewline “$i “ incr i } ….. 35 ….. 34 ….. 34 Infinite loop Correct Answer is d

48 Looping Commands Which of the following is true. (answer 2)
<test> expression in while command shouldn’t be blank <next> section of for command should contain incr command <test> section of for command should always be kept in braces ({}) Opening brace of <body> should be on the same line as for command Correct Answers are a, d a – <test> expression should never be blank in for or while commands b – <next> section can contain any code, but common use is for incr command c – It is not mandatory to keep <test> section in braces. But is recommended. d – Opening brace of <body> should be on the same line other wise TCL interpreter will assume that for or while command is completed.

49 Looping Commands What is the output of set i 10 while "$i < 20" {
incr i if "$i > 25" break puts –nonewline "$i " } … 25 … 20 … 25 Infinite loop Correct answer is c <test> expression is not kept in braces. So substitution done by TCL interpreter

50 Looping Commands What is the output of
for "set i 10" "$i < 20" "incr i" { if "$i > 25" break puts -nonewline "$i " flush stdout } … 25 … 25 Infinite Loop Doesn’t execute Correct Answer d

51 Creating commands - proc
We can create custom commands using proc command Similar to creating functions or procedures in other languages. Syntax: proc <new_cmd_name> <args> <body> A new command with name <new_cmd_name> will be created, which takes <args> as the arguments and runs <body> on calling. Example: proc sum { arg1 arg2 } { set result [expr {$arg1 + $arg2}] return $result } puts “1 + 2 is [sum 1 2]”

52 Creating commands - proc
New command can return a value to the calling command by using return command. Syntax: return <args> If no return statement is mentioned return value of the new command is return value of the last command it executes in the body. Existing commands can also be overridden by creating new commands with their name. e.g., proc while { arg1 } { puts “While is now just a puts command: $arg1” } while {true}; #It just prints text

53 Creating commands - proc
New commands can have variable number of arguments by assigning default values. proc increment { arg1 {arg2 1} } { set x [expr {$arg1 + $arg2}] return $x } puts “[increment 2]”; #Prints 3 puts “[increment 2 2]”; #Prints 4 If the last argument is args then any extra arguments while passing will be assigned to args proc command { arg1 {arg2 1} args} { command ;# arg1=1, arg2=2, args=3 4 5

54 Creating commands - proc
What is the output of following program proc area_of_rectangle { length { breadth 2}} { return [expr 2 * $length * $breadth] } puts “[area_of_rectangle 5], [area_of_rectangle 5 4]” 20, 40 50, 40 20, 9 Doesn’t execute Correct Answer is a

55 Creating commands - proc
Which of the following is correct answer Existing command’s name shouldn’t be used to create new commands Proc definition for a new command should come first before using it New command shouldn’t be called inside the body definition of the same command while creating this using proc All the above Correct Answer is b

56 Creating commands - proc
What is the output of following program proc sum { arg1 {arg2 3} arg3} { return [expr $arg1+$arg2+$arg3] } puts “[sum 1 2 3] and [sum 2 3]” 6 and 5 6 and 8 7 and 8 Doesn’t execute Correct answer d For the second call, i.e, [sum 2 3], arg1=2, arg2=3, but arg3 which is a mandatory argument has no value, so gives error

57 Variable Scoping – global, upvar
Scope is a set of lines of code in which all the variables created in that scope will be destroyed after this code and these variables can be accessed only by this code set. Entire TCL code comes under global scope. Any procedure in the TCL code creates it’s own local scope which is the body of that procedure. global command should be used to access the global variables in a local scope. No local scope variable should clash with a global variable if you are using global variable inside the local scope. Syntax: global <globalVariableName> upvar command should be used to make a local variable to be accessed from global scope ( or a scope that is one level up in the calling stack of that procedure) Syntax: upvar <level> <var1> <localVar1> … <varN> <localVarN> * <level> is optional and default is 1

58 Variable Scoping – global, upvar
proc1 (local scope) proc2

59 Variable Scoping – global, upvar
set periConstant 2 proc sum { variable value1 value2 } { upvar $variable localVar set localVar [expr {$value1+$value2}] } proc perimeterRect { variable length breadth } { global periConstant # area = 2 * (L + B) sum x $length $breadth set localVar [expr {$periConstant * $x}] perimeterRect perimeter 2 4 puts “Length = 2, breadth = 4, perimeter=$perimeter” global

60 Variable Scoping – global,upvar
Which of the following is true (answer 2) global command should be used only in global scope upvar command can make local variable to be accessible from global scope global and upvar commands shouldn’t be used in the same scope global and local variable names shouldn’t be clashed if global command is used in the local scope. Correct Answer b, d

61 Variable Scoping – global,upvar
What is the output of following code set x 10 proc sum { {x 15} y } { global x return [expr $x + $y] } puts [sum $x 20] 20 30 35 Doesn’t execute Correct answer d

62 Variable Scoping – global,upvar
What is the output of following code set x 10; set y 20; set z 30 proc sum { x y } { upvar $x result global z set result [expr {$y + $z}] } sum “y” $x puts “X: $x, Y:$y, Z:$z” X: 10, Y:40, Z:30 X: 10, Y:20, Z:30 X: 40, Y:0, Z:30 Doesn’t execute

63 TCL Data Structures - Lists
List is an ordered collection of strings/lists Multiple ways to create a list set lst {a b c} or set lst “a b c” or set lst {{a b} c} set lst [split “a.b.c” “.”] set lst [list “a” “b” “c”] split command splits a string by the separator Syntax: split <string> <separator> <separator> can contain multiple characters each will be used as separator. It is optional and by default <space> will be assumed Examples: split “Hello how are you” ;#Result: {Hello how are you} split “123456” “36”; #Result : {12 45}

64 TCL Data Structures - Lists
List operations (some important ones) lindex <list> <index> Returns the <index>th element of the list <list>. <index> starts from 0. llength <list> Returns the number of elements in the list <list> lappend <list> <arg1> <arg2> ... <argn> Appends the args to list <list>, treating each arg as a separate element. linsert  <list>  <index>  <arg1> <arg2> ... <argn> Retuns new list after adding args just before <index>th element of the list. lsearch <list> <pattern> Searches the list for pattern and returns the matching index. Returns -1 if no match found. Pattern is a glob pattern. lsort <list> Returns new list by sorting the items of <list> in alphabetical order.

65 TCL Data Structures – Lists
What is the output of following code set lst {hello how are you} set index [lsearch $lst “h*”] puts $index 1 0,1 Doesn’t execute Correct Answer b

66 TCL Data Structures – Lists – Hand’s on
Try the following programs and see what is the output Program Output set lst {{a b} c} puts “List: $lst,[lindex $lst 0]” List: {a b} c,a b set lst [split “Aug/15/1947” “/”] puts “Independence on [lindex $lst 1]th of [lindex $lst 0]” Independence on 15th of Aug lappend lst {d} {e {f g}} puts “$lst” puts “[lindex [lindex $lst 3] 1] {a b} c d {e {f g}} f g set lst {dog {zebra cow} apple} set lst [lsort $lst] puts $lst apple dog {zebra cow}

67 TCL Data Structures – Lists - foreach
List elements can be iterated using foreach command. Syntax: foreach <varName> <list> <body> Example: set lst [list “a” “{b c}” “d”] foreach element $lst { puts $element } Output of the above code is a {b c} d

68 TCL Data Structures – Lists
What is the output of following code set string [split "hello how are you" "o"] puts [lindex $string [expr [llength $string]-1]] u you are y Doesn’t execute Correct answer a

69 String operations - string
string is the command which performs string operations string length <string> Returns length of <string> Ex: puts [string length “hello how are you” ]; #OUTPUT: 17 string index <string> <index> Returns the <index>th character from string. Index starts from 0 puts [string index “hello how are you” 10]; #OUTPUT: a string range <string> <first> <last> Returns a string composed of the characters from first to last. puts [string range "hello how are you" 4 10] ; #OUTPUT o how a

70 String operations - string
string compare <string1> <string2> Returns 1 if <string1> is greater than <string2> 0 if <string1> is equal to <string2> -1 if <string1> is less than <string2> Comparison happens letter by letter by their ASCII codes string first <string1> <string2> Returns the index of a letter in <string2> which matches the letter in <string1>. First match will be considered string last<string1> <string2> Returns the index of a letter in <string2> which matches the letter in <string1>. Last match will be considered string match <pattern> <string> Returns 1 if <pattern> matches with the <string>, 0 otherwise <pattern> here is a glob pattern.

71 String operations - string
string tolower <string> Returns a string with all letters from <string> converted to lower case string toupper<string> Returns a string with all letters from <string> converted to upper case string trim <string> <trimChar> Returns a string by trimming all leading and trailing <trimChars> from <string> <trimChars> is optional and by default it is white spaces(space, tab, newline)

72 String operations - string
What is the output of following code set x “cisco” set y [string first “c” “cisco”] puts “[string range $x 1 $y]” c cisco Doesn’t execute Shows blank Correct Answer d

73 String operations - string
What is the output of following code set x “hello” set y “hello” if { [string compare $x $y] } { puts “Match found” } else { puts “Match not found” } Shows Blank Match found Match not found Doesn’t execute Correct Answer c

74 String operations - string
What is the output of following code set x “Cisco” string toupper $x puts $x Cisco CISCO cISCO Doesn’t execute Correct Answer a

75 Regular Expressions - regexp
Regular expression is used for pattern matching. regexp command does the regular expressions pattern matching. regexp <switches> <pattern> <string> <matchVar> <subMatch1>…<subMatchN> * returns the number of matches Patterns can have following characters . – Matches any single character * – Matches previous character 0 or more times + – Matches previous character 1 or more times ^ – Matches beginning of the string $ – Matches the end of the string […] – Matches any character in the set of characters in [ ] [^..] – Matches any character which is not in the set of characters in [ ]

76 Regular Expressions - regexp
Examples: set x “India got independence on 15-Aug-1947” Regexp to see a word “India” exists in ‘x’ regexp {India} $x Regexp to see a word “India” exists in ‘x’ and it is at the beginning of string. regexp {^India} $x Regexp to see a word “India” exists in ‘x’ and it is the only word. regexp {^India$} $x Match “India” followed by any text and followed by “15-Aug-1947” in ‘x’; regexp {India.*15-Aug-1947} $x

77 Regular Expressions - regexp
To match a date in the form ‘DD-MMM-YYYY’ in ‘x’ regexp {[0-9][0-9]\-[a-zA-Z][a-zA-Z][a-zA-Z]\-[0-9][0-9][0-9][0-9]} $x Can be written as regexp {[0-9]{2}\-[a-zA-Z]{3}\-[0-9]{4}} $x Write a simple regular expression to match an IP address regexp {([0-2][0-5]{2}\.){3}[0-2][0-5]{2}} “ ” Write a regular expression to see the interface Ethernet1 is up or down set x "Ethernet1 unassigned YES unset administratively down down“ if {[regexp {Ethernet1.*down} $x]} { puts "DOWN" } else { puts "UP" }

78 Regular Expressions - regexp
What is the output of following program set x “India got independence on 15-Aug-1947” if {[regexp {India*independence} $x]} { puts “Match found” } else { puts “Match not found” } Match found Match not found Shows blank Doesn’t execute Correct Answer b

79 Regular Expressions - regexp
Extracting matching sub string from a string set x “India got independence on 15-Aug-1947” Extract date from ‘x’ regexp {.*([0-9]{2})\-([a-zA-Z]{3})\-([0-9]{4})} $x full day mon year Identify the class of the ip address in following program set x “Ethernet YES NVRAM up up”

80 Arrays - array TCL supports arrays as in any other languages. Index of the array is a string Example: set color(sky) blue set color(grass) green set item “grass” puts “$color(sky) and $color($item)” global color makes all the elements of array “color” to be accessible by the procedure. Can we use integers as indexes to Arrays? Yes. After all every thing is a string in TCL

81 Arrays - array array exists <arrayName> Returns 1 if <arrayName> exists or 0 if <arrayName> is a scalar variable, proc or doesn’t exist. array names <arrayName> <pattern> Returns the list of indices of array <arrayName>. <pattern> is optional and if exists returns the indices matching with <pattern> Indices may not be returned in the order that are created. array size <arraySize> Returns the number of elements in the array array set <arrayName> <list> Creates an array <arrayName> with all odd (1,3,5..) element as index and the next element as value in that index

82 Arrays - array Example: array set color [list {sky} {blue} \
{grass} {green} ] if {[array exists color]} { puts “Size of array is : [array size color]” puts “Items of the array color are: ” foreach item [array names color] { puts –nonewline “$color($item)” } flush stdout

83 Arrays - array What is the output of following code set color “blue”
set color(apple) “red” puts $color blue {blue red} blue red Doesn’t execute Correct answer d Same variable name shouldn’t be used for scalars and arrays

84 Arrays - array What is the output of following code
set array “{hello how are you}” if { [array exists array] } { puts “$array” } else { puts “Array doesn’t exist” } hello how are you {hello how are you} Array doesn’t exist Doesn’t execute Correct Answer c

85 File operations There are lot of file operation commands in TCL.
To open a file open <filename> <accessArgument> Example: set fileId [open /tmp/temp.txt w] puts $fileId “Hello how are you” Access Arguments: r - Read Only. File must exist r+ - Read and write. File must exist w - Write only. Truncates if exist. Creates if doesn’t exist w+ - Read and write. Truncates if exist. Creates if doesn’t exist a - Write only. Data will be appended to the file a+ - Read and write. Data will be appended to the file

86 File operations - Reading
set infile [open "myfile.txt" r] set number 0 while { [gets $infile line] >= 0 } { incr number } close $infile puts "Number of lines: $number"

87 File operations - file file command :
file copy source destination Copy file source to file destination. file delete name Delete the named file. file dirname name Return parent directory of file name. file executable name Return 1 if name has execute permission, else 0. file exists name Return 1 if name exists, else 0. file isdirectory name Return 1 if name is a directory, else 0. file mkdir name Create directory name. file rename old new Change the name of old to new. file size name Return the number of bytes in name.

88 Running external programs - exec
We can run external programs or shell commands from TCL using exec command Syntax: exec <command> <argsToCommand> Example: exec ls *.tcl What happens if I run exec “ls *.tcl” Gives Error couldn't execute "ls *.tcl": no such file or directory and program aborts We shouldn’t enclose the command and its arguments with grouping characters like quotes (“”) or braces ({}) But how to make TCL not to abort incase of the errors as shown above?

89 Exception Handling - catch
Run any TCL code inside catch command to catch any run time exception that TCL returns without aborting the program. Syntax: catch <TCLCode> <error> <TCLCode> - Any tcl code that may throw error <error> - Optional variable to store the error message. Example: catch { puts hello how are you } catch { exec “ls *.tcl” } msg puts “$msg”

90 exec, catch What is the output of following code
set command “echo Cisco” catch {exec $command} output puts $output Cisco echo Cisco exec $command couldn't execute "echo Cisco": no such file or directory Correct Answer d

91 exec, catch What is the output of following code
set command “echo Cisco” catch “exec $command” output puts $output Cisco echo Cisco exec $command Doesn’t execute Correct Answer a

92 Existence of variables/commands - info
info commands provide flexibility to talk to TCL interpreter to get the information about variables and procedures. info exists <varName> Returns 1 if the variable with name <varName> exists 0 otherwise info globals <pattern> Returns list of all global variables that match <pattern> info locals <pattern> Returns list of all local variables that match <pattern> info procs <pattern> Returns list of procedures that match <pattern> info vars <pattern> Returns list of global, local variables that match <pattern>

93 Existence of variables/commands - info
Example: set variable “Hello” if { [info exists variable] } { puts “Variable exists” } else { puts “Variable doesn’t exist” }


Download ppt "TCL Training Joshi Sravan Kumar K 21-Nov-2011."

Similar presentations


Ads by Google