Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List manipulation in Tcl

Tags:

tcl

I have a list which I am trying to modify and make a new list based on what I am trying to achieve.

Original List

$> set a {123.4:xyz 123.4:pqr 123.4:xyz 123.4:abc 123.4:mno}
$> puts $a
$> 123.4:xyz 123.4:pqr 123.4:xyz 123.4:abc 123.4:mno

I want my new list to contain following elements

$> puts $a
$> xyz pqr xyz abc mno

I tried split $a : but it did not work out for me. Please suggest what can be done.

like image 670
user2643899 Avatar asked Nov 30 '25 14:11

user2643899


2 Answers

set b [list]
foreach item $a {
    catch { 
        regexp {\:(.*)} $item match tail 
        lappend b $tail
    }
}
puts $b

It's possible to do above with split instead of regexp; I prefer regexp because you can extract arbitrary patterns this way.

like image 64
Michael Avatar answered Dec 04 '25 09:12

Michael


If you've got Tcl 8.6:

set a [lmap x $x {regsub {^[^:]*:} $x ""}]

In 8.5, it's easier if you store in another variable:

set b {}
foreach x $a {
    lappend b [regsub {^[^:]*:} $x ""]
}

In 8.4 and before, you also need a slightly different syntax for regsub:

set b {}
foreach x $a {
    # Mandatory write back to a variable...
    regsub {^[^:]*:} $x "" x
    # Store the value; it isn't reflected back into the source list by [foreach]
    lappend b $x
}
like image 27
Donal Fellows Avatar answered Dec 04 '25 10:12

Donal Fellows