How to Assign a List’s Elements to Variables

The Problem

You want to assign the contents of a list to a number of variables. For example, assigning contents of $argv to variables server, port, user, and password:

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

The Solution

This is what the lassign command is designed to do, see my previous post. However, prior to Tcl version 8.5, using lassign means you must load the entire TclX package, which might be expensive for one little command.

If you don’t want to require the whole TclX package just for this task, here is another alternative solution: using the foreach idiom:

foreach {server port user password} $argv break

The above is the same as using lassign:

package require Tclx
lassign $argv server port user password

2 thoughts on “How to Assign a List’s Elements to Variables

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