MBA 683 E-Business Technology --

Ref: TCL
Home    Site Map    Search    EhrlichOrg.com

Syllabus    Classes    References  Examples  Student Info    Guest Info

 

TCL References

The TCL (pronounced 'tickle') programming language is supported by the AOL server environment that we are using for this course.  TCL programs can be embedded into Web pages and will be executed automatically when the page is accessed.  This is an extremely convenient way to develop programs that avoids all the software tools and compiling steps required for other programming languages.

This page provides a short guide to the subset of TCL you will need for this course.  See also additional references.

TCL code can be executed four ways, we primarily use the first alternative:

  1. Files with the .adp extension may contain embedded TCL scripts enclosed between <% and %> tags, these scripts should use ns_adp_puts to write to the browser.  
  2. ADP files may contain TCL code enclosed in <%= and %>, the result of this code is written automatically.  However, we will use only the <% %> form because its easier to test.
  3. Files with the .tcl extension contain TCL code that is executed when the page is referenced.  The code may create Web pages or do other things.
  4. Run TCL under Linux by typing tclsh.  

TCL variables:

Are all essentially string variables.  TCL is very flexible about data types.
Names may be any length and may contain letters, numbers, and underscore (like SQL).  Case is significant in variable names, use only lower case letters.
Do not have to be declared before they are set.
Must be set before they are referenced.

 

TCL Syntax

Commands are terminated by the end of a line (called a newline) or a semicolon.

Whitespace (space or tab) is used to separate commands and arguments.

# indicated that rest of the line is a comment.  A backslash continues a comment to another line.  Use ;# to put a comment on the same line as a command.  Note that comments should only appear between TCL commands.  Comments embedded inside TCL commands may cause problems.

$ dollar sign returns the value of a variable.

[ ] brackets are used to nest commands.

Double quotes " " or curly braces { }  are used to group words together into one argument.  Quotes allow substitution (evaluation) of the contents, curly braces prevent substitution.

\ backslash is used to allow substituting characters that would otherwise have special meaning to TCL such as newline (\n).  Use \ to quote TCL special characters:

\” quote
\\ backslash
\$ dollar sign
\n new line character
\{ \} braces
 \[ \] brackets
TCL Commands

set variable [exp].  For example the TCL equivalent of a=b is 

set a $b

expr evaluate an arithmetic expression (see Arithmetic Operators below).  The TCL equivalent of a=b+2 is:

set a [expr $b +2 ]

incr var, increment command adds one to a variable.  The equivalent of c=c+1 or c++ in C or Java is:

incr c

ns_adp_puts writes a string to the client.  In ADP pages, use ns_adp_puts instead puts or ns_write.  

ns_adp_puts "the value of a is $a."

format forms values according to a formatting specification and value like this:

format "%2.2f" $pure

Format may be used inside the string for ns_adp_puts like this:

ns_adp_puts "value is [format "%2.2f" $pure]% pure"

If $pure equals 99.98765 the result will be:

value is 99.99% pure

Format specifications are enclosed in quotes, begin with % followed by the formatting flags and ends with the format type.  Format flags include the number of characters as well as the following values:

- left justify the value
+ always include either a + or - sign
space include either a space or a minus sign

Format types include:

f floating point or real numbers.  For example, "% 4.2f" specifies a number with an optional sign, 4 digits to the left of the decimal and 2 digits to the right.
d signed integer
u unsigned integer
s string.  For example, "%-10s" specifies a left justified 10 character string, "%10s" specifies a right justified 10 character string. 
e or E, use scientific notation.  For example: "%e" results in 9.998765e+2.

If then, if then else conditional commands (comparison operators are defined below) are shown below.  The then command is optional.  

If {$x==0} {
    incr zero_count
} else {
    incr non_zero_count
}

Compound conditional statements may be created using elseif. 

If {$x==0} {
    incr zero_count
} elseif {$x<0} {
    incr neg_count
} else {
    incr pos_count
}

While loop with test clause and body.  Note that the condition ($x<=10) must be enclosed in braces ({$x<=10}) or an infinite loop will result.

Set x 1
While {$x<=10} {
    ns_adp_puts ‘line $x<br>’
    incr x
}

Info exists, test if a TCL variable has been defined.  Note that HTML Form variables will not be defined if the field is omitted.  Use info exists to check and provide an error message or a default value.

if {![info exists foo]||[$foo==""] } {
    ns_adp_puts "You must enter a value!"
    }

TCL String Operations
Convert to uppercase: string toupper $sname
Convert to lowercase: string tolower $sname
Remove leading and trailing blanks: string trim $sname
Remove leading blanks: string trimleft $sname
Remove trailing blanks: string trimright $sname
Number of characters in string: string length $sname

For example:

set a [string toupper $a ]

TCL Operators 

! is logical Not

* Multiply, / Divide, % Remainder

+ Add, - Subtract

< Less Than, <= Less Than or Equal

> Greater Than, >= Greater Than or Equal 

== test for Equal

!= test for Not Equal

&& is logical And

|| is logical Or

Note: logical operators treat 1 as true and 0 as false.

TCL Library Routines and AOL Server API Calls

ns_adp_puts writes output to the user's browser window from .adp pages. 

ns_adp_puts expression

Displays the results of a TCL expression. Use $name to display TCL variable values. Examples:

ns_adp_puts "<p>*** end ***<p>"
ns_adp_puts "$sid: $sname<br>"

db_foreach executes a SQL query and then executes some TCL code for each row returned by the database. The unconditional form is:

db_foreach s-name "SQL query" {
code-block-1
}

Example:

db_foreach s_row "select sid, sname from chuck.s order by sid" {
ns_adp_puts "$sid: $sname<br>"
}

Notes:
The s-name value must be unique on each page
Executes the SQL query
Creates a TCL variable for each column name returned
Executes code-block-1 for each row returned by Oracle
The { must be on the same line as the SQL query
The code block may contain break statements (which terminate the loop) or continue statements (which continue to the next row of the loop).

The conditional form executes code-block-2 if no rows are returned.

db_foreach s-name "SQL query" {
  code-block-1
} if_no_rows {
  code-block-2
}

Example:

db_foreach row "select sid, sname from chuck.s where sid=99" {
  ns_adp_puts "$sid: $sname<br>"
} if_no_rows {
  ns_adp_puts "No records found!<br>"
}

db_dml executes a SQL Data Manipulation Language command such as Insert, Update or Delete. Basic pattern is:

db_dml s_name "SQL command"

Example: 

db_dml s_row "insert into chuck.s (sid, sname) values ($sid,'$QQsname')"

db_resultrows returns the number of rows affected by the previous db_dml statement. For example:

set nrows [db_resultrows]

db_1row performs an SQL query and sets values equal to column names. Results in an error if the query does not return exactly one row. For example:

db_1row s_row "select sid, sname from chuck.s where sid=99"

db_0or1row performs an SQL query and returns these possible results:
No matching rows, returns 0
One matching row, returns 1 and sets variables based on column names.
More than one matching row, reports (throws) a TCL error.

set nrows [db_0or1row s_row "select sid, sname from chuck.s where sid=99"]

db_nextval returns the next value of an Oracle Sequence. Multiple calls within the same logical database row will return the same value. For example: 

set seq_val [db_nextval usf_seq]

ns_dbquotevalue prepares a string value for inclusion in an SQL statement by adding quotes and doubling any single quotes included in the string.  Empty strings ("") are translated to NULL.

set value "Wonka's Wonder"
ns_db dml $db \
"insert into s(sname) values ([ns_dbquotevalue $value])"

ad_set_cookie will create a browser cookie with the specified name and value. The simple form is:

ad_set_cookie player_id $id

There are also these optional arguments that may specified after ad_set_cookie and before the name and value:
-replace (defaults to "f")
-secure (defaults to "f")
-expires (optional, "never" or a date in the form "Sat Apr 3 23:12:34 PST 1999")
-max_age (optional)
-domain (optional)
-path (defaults to "/")

Notes:
Cookies are deleted by setting an expire date in the past:
ad_set_cookie -expires "Sat Apr 3 23:12:34 PST 1999" player_id $id
The following command formats the current time for a cookie (see ns_fmttime below):
ns_fmttime [ns_time] %a %b %e %T %Z %Y

ad_get_cookie returns the value of the browser cookie with the specified name or the default value if there is no cookie with that name.

ad_get_cookie c_name c_default

For example, this statement sets c_val to the cookie value or "n/a":

set c_val [ad_get_cookie player_id n/a]

ns_time returns the current system date and time as the number of seconds since 00:00:00 UTC, January 1, 1970. Use ns_fmttime (below) to format the results.

ns_fmttime formats server time (ns_time) values.  For example: 

ns_fmttime [ns_time] "%A, %B %e, %Y at %r"

Options include: Weekday short (%a) or long (%A), Month name short (%b) or long (%B), Day of month (%e), Year short (%y) or long (%Y), Time hh:mm:ss xM (%r), 24 hour time hh:mm:ss (%T), or hh:mm (%R),  time zone (%Z), etc.

ad_returnredirect switches the user to a different page by sending an HTTP redirect message.  Used in a helper page to send the user back to the main page (which will be refreshed) if the operation is successful and there are no error messages to show the user.  TCL commands following the call to ad_returnredirect will be executed (this command only sends the redirect message), either design your code to handle this or call ns_adp_abort as shown in the example below.

For example:

ad_returnredirect "s-main.adp"
ns_adp_abort <<AD_SCRIPT_ABORT>>

set_form_variables creates TCL variables with the same names as form fields.  Use set_the_usual_form_variables (below) instead so you have the QQ quoted versions of strings.    

set_the_usual_form_variables is like set_form_variables but also makes QQ versions of fields names for handling quoted strings correctly.  It is a good idea to include a comment listing the variables that you expect this routine to create.

set_the_usual_form_variables
# sets sid, QQsid, 
#  sname, QQsname

Note that HTML form fields that are not filled in, checked or selected do not pass any value, consequently variables will not be created for these fields.  If no values are passed the user may get a HTTP 500 Server Error message.  To avoid having the user get this errors, specify a 0 for the error predicate as shown below and test for the existence of each variable.

set_the_usual_form_variables 0
# sets sid, QQsid, 
#  sname, QQsname

You can use info exists to test for a value and give return a message as shown above.  An alternative is to use the function export_var to provide a default value like this: 

set course [export_var course "n/a"]

Other TCL Examples

See http://usf-acs.rho.net/tech/ 

Greenspun pages 378, 442, 467, 510, and 515. Note that the book uses the old TCL API.

Additional References

For more information on TCL see:

TCL Developers Exchange http://dev.scriptics.com/ including:
TCL Introduction http://dev.scriptics.com/scripting/primer.html
TCL Syntax http://dev.scriptics.com/scripting/syntax.html
Getting Started http://dev.scriptics.com/scripting/ 
TCL for Web Nerds by Hal Abelson, Philip Greenspun, and Lydia Sandon
Scriptics Corporation, http://www.scriptics.com/ 
Tcl manual pages, http://www.scriptics.com/man
TCL Quick Reference Manual
Practical Programming in Tcl and Tk third edition by Brent B. Welch, Prentice Hall, 1999
Tcl and the Tk Toolkit by John K. Ousterhout, Addison-Wesley, 1994
Developers Guide http://www.arsdigita.com/doc/developers.html 
Common Errors in applications http://www.arsdigita.com/doc/common-errors.html 

Note: we are not using Tk, a toolkit for building graphical user interfaces. 

 

© 2001 by Chuck Ehrlich, all rights reserved.  Comments to webmaster.  Updated on April 18, 2001.