Tcl: SPLIT Command

Posted: May 17, 2011 in Tutorials
Tags: ,

In Tcl (Tool command language), split command can be used to convert a string into list. Converting lists from string allows you to process the part of string with list commands.

Syntax:
split string ?splitChars?

where string is the string that needs to be converted into list elements.
where splitchars is words based on which string is splitted into list elements. This is an optional argument and its default value is empty space.

How it works ?

Split command locates all the instances of any of the split character in the string based on which string would be split-ed. If you are passing multiple split characters then that needs to be quoted properly.

After locating split characters in the string, it returns list elements that lies between these located split characters. Ends of the string are also treated as split characters. So if adjacent split characters are defined or the split character appears at the end of string an empty list element will be returned. Following examples will illustrate these points.

Eg1:
set str1 /usr/bin/http
split $str1 /

=> {{} usr bin http}

In this example first element is {} because split command will treat string end as split character. So it will return characters between string -end and “/” which turns out to be an empty list element.

Eg2:
set str2 “This is some text”
split $str2

=>{This is some text}

In this example as no split character is provided as an argument, split command returns a list with four elements.

Eg3:
set str3 “<</abc/def”
split $str3 <<

=> {} {} /abc/def

In this example as string as “<” two times, so split will return one empty list element between string-end and first instance of “<” and second between first and second instance of “<”.

Eg4:

set str abcdeab

split $str ab

=> {} {} cde {} {}

In this example multiple split characters are used based on which string is converted to list.

Eg5:
set str5 “abc def”
split $str5 “c d”

=> ab {} {} ef

Now in this case there are three split characters i.e. c,d and empty space, so two empty list elements are returned.

Eg6: (Trick to split each character of a string into list element)
set str6 abcdef
split $str6 {}

=> a b c d e f

Advertisement

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 )

Connecting to %s