Testing with Patterns Before Execution with case
Some commands return a list such as a list of objects in a directory or a list of servers running on a host system. You can use the case command to test a list or string for
specific patterns such as the name of a particular object or server. On detecting a specified pattern, the case command then executes a script associated with the pattern detected. The
general syntax for the case command is:
case string in pattern {script} pattern {script}
The case command looks in string for pattern and executes {script}. The word in can be omitted. The following example illustrates how the case
command works.
dcecp> set x {one ten twenty} one ten twenty dcecp> foreach el $x {case $el in one {puts script1} two {puts script2}} script1
dcecp>
The case command first checks in $x variable for the pattern one. On finding this pattern, the associated script echos script 1 on the display. When it
finds no more matches, the case command ends.
For a more practical example, say you run a dcecp command that lists all the servers on a particular system. You could search the list for particular server names and execute a script that
appends each name to a particular file.
case $x in server1 {lappend filename1} server2 {lappend filename2}
If your list of patterns is lengthy and likely to break across lines, you can prevent newlines from being interpreted as separators by enclosing the entire list of target patterns and scripts in
braces. This has the additional benefit of preventing variable and command substitutions in the braced list.
Patterns can include wildcard characters. A question mark (?) in a search pattern matches the corresponding character in the target pattern. For instance, ?at matches
bat, cat and hat. An asterisk (*) in a search pattern matches any string in the target pattern. For instance *at matches bat,
chat, and "three cornered hat" (note the use of double-quotes to disable spaces as separators).
You might want a way to execute some default script when no pattern matches are found. The case command has a special pattern called default whose corresponding script executes
when no pattern match is found. You should place the default pattern as the last position in the list:
case $x in { a {puts "script for case a"} b {puts "script for case b"} default {puts "run this script if no matches are found"} }
|