Main Content

Calling procs in Tcl and how it compares to Perl

Archive - Originally posted on "The Horse's Mouth" - 2008-09-02 18:19:55 - Graham Ellis

In languages such as Java, you must call your named blocks of code (methods) with the correct number and type of parameters, but in Perl you may call them with as many or as few parameters as you like ... then write the named block of code (a sub) to handle (or ignore) whatever it gets.

This week, I'm running a Tcl Course in Cambridge for a group of delegates who are already familiar with Perl (and some other languages) and I'm showing them how things differ in Tcl. Here are some of the contrasts ...

1. Since Tcl is a true interpreter, you MUST define your procs earlier in your code than the code that calls it.

2. Since Tcl is a true interpreter, you MAY define your procs conditionally - for example you could have an "if .... else" command, and define something different - but using the same name - depending on a test

3. In Tcl, you can redefine a proc while your script is running - you won't get the "doubly defined" error of "C", and the interpretive nature of the language (as oposed to Perl, which is pseudoscripting only, means you don't have a compile phase at which all procs must be defined.

4. When you declare a proc, you specify the number of parameters - for example
proc cardpack {suites ranks} { ....
is how you would define a proc that takes two parameters

5. You may add a list within a list for optional parameters - for example
proc cardpack {suits {ranks 13} {jokers 0}} { ...
which defines a proc that takes one, two of three parameters - but not zero, nor four or more. If you give just one parameter, it's put into the variable calls $suits and $ranks defaults to 13 and $jokers to 0.

6. If you want to accept an indeterminate number of parameters, you use the special name args for the final parameter, and that acts like a sponge to collect all remaining parameter valuse as a list within the proc - for example
proc hand {firstcard secondcard args} { ...
called with
hand 13 17 75 32 32 44 32
would store 13 in $firstcard, 17 in $secondcard, and all the rest into a list in $args - that's {75 32 32 44 32}.

7. In Tcl you are calling by value, so information passed in to a proc is in effect copied in there, and if you alter it you are not altering the original in the calling code. If you want to alter the value within the proc, you'll need to pass in the variable name and use upvar

8. You may pass arrays in to procs - but you must call by name / use upvar

In Perl, variables default to being our or global, but in Tcl they default to being local. You may declare them global if you like.