Passing Arguments to an User-Defined Proc in Tcl using VLSI

www.spiroprojects.com



Passing arguments to any procedure is a very common scripting style. In this post we will discuss two ways one can pass arguments to any procedure in Tcl.

Just like the last post, Reading from and writing to a file in tcl, the text in black represents tcl commands. Text in red represents user-defined variables.

The conventional way to pass arguments to a user-defined procedure (palindrome, in this case) in Tcl is:

proc palindrome { arg1 arg2 } {
<body of the proc using $arg1 and $arg2>
}

The above proc is then called like: palindrome <arg1> <arg2>

The order of passing these arguments need to be maintained.
The above approach works fine. However, when the number of arguments is large, one needs to remember the relevance of each argument and their order of occurrence.

Here's a more versatile way of passing the arguments:

 proc palindrome { args } {
    variable args_list {}
    set valid_switches [list "-description_arg1" "-description_arg2"]
    parse_proc_args $args $valid_switches palindrome

    set arg1           [cdr [assoc "description_arg1"          $args_list]]
    set arg2           [cdr [assoc "description_arg2"          $args_list]]
<body of the proc using $arg1 and $arg2>
}
The above proc is called like: palindrome -description_arg1 <arg1> -description_arg2 <arg2>


Here you can always associate the "description_arg1" keyword with arg1 and so on. Moreover, it is not necessary to call arg1 before arg2.
You can also use: palindrome -description_arg2 <arg2> -description_arg1 <arg1>
  All you gotta make sure is that you associate the arguments with the corresponding description switch!

                       

 
Previous
Next Post »