PreviousNext

Operating on Lists

Lists provide convenient ways to operate on collections of things such as sets of principals, group members, or other objects. Lists are collections of objects entered by you or returned from commands. We've already seen lists in previous examples in this topic - they are any number of elements separated by spaces, tabs, or newlines. Usually, a list is enclosed in braces. All of the following are examples of lists.

{n_long l_jones p_sawyer d_witt m_dougherty s_preska}

{{/.:/hosts} {/.:/subsys}}

The dcecp program relies on lists to group elements so they can be correctly parsed by the dcecp command interpreter. For example, the set command takes two arguments:

set varName value

The following set command cannot be correctly parsed because dcecp detects a third argument.

dcecp> set a John Hunter
Error: wrong # args: should be "set varName ?newValue?"
dcecp>

Use braces, quotes, or backslashes to create a valid list, as follows:

dcecp> set a {John Hunter}
John Hunter
dcecp> set a "John Hunter"
John Hunter
dcecp> set a John\ Hunter
John Hunter
dcecp>

The commands that operate on lists provide convenient ways to evaluate, select, and act on individual elements or groups of elements in a list. The dcecp program provides a comprehensive set of commands that let you create, modify, search, sort, and convert to and from lists.

For example, the following script returns the last element in a list. The llength command returns the number of elements in the list. Our list has four elements so llength returns 4. The dcecp program numbers the elements from left to right starting with 0 so our list with three elements has elements numbered 0, 1, 2, and 3. The value of variable c is set to the number of the last element in the list (3). Finally the lindex command returns element 2 (f).

dcecp> set a {a b {c d e} f}
a b {c d e} f
dcecp> set b [llength $a]
4
dcecp> set c [expr $b-1]
3
dcecp> lindex $a $c
f
dcecp>

The dcecp program provides numerous commands for working with lists. You can join lists together using the concat command. Use linsert to add elements to an existing list. Extract a range of elements using lrange, replace elements in a list with lreplace, and sort list elements in alphabetical (dictionary) order using lsort. The dcecp program also includes an attrlist object (see attrlist(8dce) for use in manipulating list elements.

Here's an example that lists all child directories in a tree in alphabetic order. _r is a dcecp convenience variable that holds the output of the last command. In this case, _r holds the list of directories returned by the directory list -simple command.

dcecp> directory list -simple /.:
hosts subsys cell-profile fs lan-profile planets_ch sec sec-v1
dcecp> lsort $_r
cell-profile fs hosts lan-profile planets_ch sec sec-v1 subsys
dcecp>