split(3tcl)

πŸ’– split(3tcl) πŸ’–

okay bestie, welcome to split from the Tcl Built-In Commands squad 🫢 she's a tiny little icon and she does exactly one thing but she does it so well.


✨ NAME ✨

split β€” split a string into a proper Tcl list πŸŽ€


✨ SYNOPSIS ✨

split string ?splitChars?

✨ DESCRIPTION ✨

okay so here's the vibe: split hands you back a list, and that list was made by chopping up string at every single character that shows up in the splitChars argument πŸ”₯

every element of that result list? it's just the characters from string that were chillin' between the instances of the characters in splitChars. that's it, that's the whole job πŸ’…

now, the messy part (iykyk): you will get empty list elements generated when:

  • string contains adjacent characters that are in splitChars 😭
  • the first character of string is in splitChars πŸ™ˆ
  • the last character of string is in splitChars πŸ’€

and if splitChars is an empty string? then literally every character of string becomes its own separate element of the result list. one char, one slot, main character energy ⭐

splitChars defaults to the standard white-space characters 🌸 (yes it just handles it for you, no cap).


✨ EXAMPLES ✨

dividing a USENET group name into its hierarchical components πŸ¦‹

split "comp.lang.tcl" .
      β†’ comp lang tcl

see how the split command splits on every character in splitChars, which can result in information loss if you are not careful 😭 (this is your warning, bestie, pay attention)

split "alpha beta gamma" "temp"
      β†’ al {ha b} {} {a ga} {} a

extract the list words from a string that is not a well-formed list πŸŽ€

split "Example with {unbalanced brace character"
      β†’ Example with \{unbalanced brace character

split a string into its constituent characters πŸ‘‘

split "Hello world" {}
      β†’ H e l l o { } w o r l d

🌈 PARSING RECORD-ORIENTED FILES 🌈

parse a Unix /etc/passwd file, which consists of one entry per line, with each line consisting of a colon-separated list of fields πŸ“

## Read the file
set fid [open /etc/passwd]
set content [read $fid]
close $fid

## Split into records on newlines
set records [split $content "\n"]

## Iterate over the records
foreach rec $records {

    ## Split into fields on colons
    set fields [split $rec ":"]

    ## Assign fields to variables and print some out...
    lassign $fields \
            userName password uid grp longName homeDir shell
    puts "$longName uses [file tail $shell] for a login shell"
}

✨ SEE ALSO ✨


✨ KEYWORDS ✨

list, split, string πŸ’œ


and that's the whole page, bestie β€” she lives in the Tcl collection as split(3tcl), so go forth and split responsibly πŸ§šπŸ’–