Posted to tcl by colin at Mon Jun 25 05:59:54 GMT 2012view pretty

proc quopar {str {q \"}} {
    set depth 0
    set result {}
    set skip 0
    foreach c [split $str ""] {
	if {$c eq "\\"} {
	    append run $c
	    incr skip
	} elseif {$skip} {
	    append run $c
	    set skip 0
	    continue
	}
	if {$c eq $q} {
	    if {[info exists run]} {
		lappend result $depth $run
		unset run
	    }
	    set depth [expr {($depth+1)%2}]
	} else {
	    append run $c
	}
    }

    if {$depth > 0} {
	error "quopar dangling '$q' in '$str'"
    }
    if {[info exists run]} {
	lappend result $depth $run
    }
    return $result
}

if {[info exists argv0] && $argv0 eq [info script]} {
    package require tcltest
    namespace import ::tcltest::*
    verbose {pass fail error}
    set count 0
    foreach {str result} {
	{""} ""
	{"\""} {1 {\\"}}
	{""""} ""
	{"moop"} "1 moop"
	{pebbles "fred wilma" bambam "barney betty"} "0 {pebbles } 1 {fred wilma} 0 { bambam } 1 {barney betty}"
    } {
	test quopar-[incr count] {} -body {
	    quopar $str
	} -result $result
    }

    foreach {str} {
	{"}
	{"""}
    } {
	test quopar-[incr count] {} -body {
	    quopar $str
	} -match glob -result * -returnCodes 1
    }
}