Hello Script for Tcl

Tcl Logo

Tcl, or Tool Command Language, will not be found in the ‘most popular languages’ hall of fame. That is partly because of its ‘wierd’ syntax. But those who know Tcl will tell you that Tcl is a pleasure to work with. I have a special interest in Tcl – its the language that introduced me to GUI programming(Tcl/Tk). Now, when ever I see a GUI toolkit, I compare it to Tcl.

I have a few years experience in Tcl – I have written a very popular Tcl/Tk Tutorial and also a few small applications in Tcl. I am not using it a lot now a days because Tk apps look really bad in Linux. This problem is not present in Windows.

Hello Code


#!/usr/bin/tclsh

# Printing(IO)
puts "Hello World!\n" 

# Variables, concatenation
set name 'Binny' 
set year 2008 
puts [concat "Hello, "  $name  " - welcome to "  $year]

#If,else conditions
if { $year > 2008 } {
	 puts "Welcome to the future - yes, we have flying cars!" 

} elseif { $year < 2008 }  {
	 puts "The past - please don't change anything. Don't step on any butterflies. And for the sake of all that's good and holy, stay away from your parents!" 

} else {
	 puts "Anything wrong with your time machine? You have not gone anywhere, kiddo." 
}

# For loop
for { set i 0 } { $i<3 } { incr i  }  { 
	 puts "$i) Hi there!" 
}

#Numerical Array, foreach
set rules [list "Do no harm" "Obey" "Continue Living"]

set i 0
while { $i < [llength $rules] } {
	puts [concat "Rule " [expr $i+1] " : "  [lindex $rules $i]]
	incr i 
}

# Associated array, while
array set associated {
	hello	"world"
	foo		"bar"
	lorem	"ipsum"
}

foreach key [array names associated] {
	 puts [concat $key " : " $associated($key)]
}

# Using Join and Split
set csv_values [split "hello,world,how,are,you\n" ","]
puts [join $csv_values ":"]

# Function, argument, return, call
proc hello { person_name } {
	return [concat "Hello, " $person_name]
}
puts [hello "Binny"]

# File IO
# File reading, easy method...
set IN [open "Hello.tcl" r]
set contents [read $IN]
close $IN
puts [concat "Hello has " [string length $contents] " chars"]

# Writing to a file
set OUT [open "/tmp/hello.txt" w]
puts $OUT "Hello World"
close $OUT

# Regular Expressions
set str "Hello World" 
if { [regexp {^Hell} $str] } {
	puts "Yup, its evil"
}

puts [regsub -all {l([^l])} $str {\1}]

# Special Tcl Syntax
# Math ops
set answer [expr {3 + 2}]

# Comments
puts $answer ;# Comments in the same line as code must use ;# instead of just #

Tcl/Tk Links