Use lassign to Assign Command-Line Parameters to Variables

The Problem

You need to assign command-line parameters to variables. For example:

    set [lindex $argv 0] server
    set [lindex $argv 1] port
    set [lindex $argv 2] user
    set [lindex $argv 3] password

The problem with this approach is it takes lots of typing. Cut and paste can help reducing some of it, but it is error prone for the user might forget to edit the index numbers after pasting. When the number of command-line parameters increase, so is the chance for making error.

The Solution

One way to deal with assigning command-line parameters to variables is to use the lassign command from the Tclx package:

    package require Tclx
    lassign $argv server port user password

Not only this approach is cleaner and less error prone, it is also easier to understand. The user must make sure argv has enough elements to assign to the variables. If there is more variables than the number of command-line parameters, then the extra variables will be assigned the empty value {}:

    % lassign {1 2} a b c
    % puts "a=$a, b=$b, c=$c"
    a=1, b=2, c=

If there are more command-line parameters than variables, then lassign will return a list of unassigned parameters:

    % lassign {1 2 3 4 5} a b c
    4 5

Conclusion

The lassign command eases the task of assigning command-line parameters to variables. The user must exercise care to ensure the number of parameters matches the number of variables. Lassign can also be used for any list-variable assignment task the user can think of. Please take a look at the document for more usage and behavior notes.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s