Saturday, June 5, 2021

TCL Programming Basic Practice Exercises /Examples 1

🧠 TCL Programming Basic Practice Exercises / Examples (Part 1)

Hello friends! 👋
Welcome once again!

In this post, we’ll go through some basic yet powerful TCL programming exercises to help you strengthen your logic, scripting skills, and confidence in automation.


🔹 1. Swapping Variables

Using a Temporary Variable

set a 100 set b 50 set c $a set a $b set b $c puts $a ;# Output: 50 puts $b ;# Output: 100

Without Using a Temporary Variable

set a 100 set b 50 set a [expr $a + $b] set b [expr $a - $b] set a [expr $a - $b] puts $a ;# Output: 50 puts $b ;# Output: 100

🔹 2. List to String Conversion

set a "" set b "1 2 3 4 5 6" for {set i 0} {$i+1 < [llength $b]} {incr i} { append a [lindex $b $i] } puts "$a" puts [llength $a]

String to List Conversion

set a "abcdef" set b [split $a ""] puts $b puts [llength $a] puts [llength $b]

📝 Note:
There’s no difference between a string and a single-element list in data structure terms.


🔹 3. Multiply Two Numbers Without Using the Multiplication Operator

set a 5 set b 4 set c 0 for {set i 0} {$i <= $b} {incr i} { set c [expr $a + $c] puts $c ;# Verification } puts "Final: $c"

🔹 4. Namespace Example

Object-oriented style code using namespaces 👇

namespace eval sample { proc sum {m n} { set add [expr $m + $n] return $add } } puts [sample::sum 4 4]

Each namespace allows variables with the same name without conflict — making large programs easier to manage.


🔹 5. String Manipulation Examples

set str1 "cisco" set str2 "systems" puts [string compare $str1 $str2] ;# -1 puts [string equal $str1 $str2] ;# 0 puts [string first is $str1] ;# 1 puts [string first co $str1] ;# 3 puts [string first c $str1] ;# 0 puts [string index $str1 2] ;# s puts [string length $str1] ;# 5 puts [string range $str1 2 4] ;# sco puts [string range $str1 2 end] ;# sco puts [string toupper $str1] ;# CISCO puts [string tolower [string toupper $str1]] ;# cisco puts [string trim $str1 o] ;# cisc

🌟 Summary

These examples build your foundation in TCL scripting, covering variables, loops, lists, namespaces, and string operations.
Practice regularly to enhance your CAE automation and logic development skills.

Thank you for reading! 🙏
Keep exploring and stay tuned for Part 2 for more advanced TCL examples!

No comments:

Post a Comment

Thank you !

Time

Search This Blog

Contact Form

Name

Email *

Message *