Stream merge: Difference between revisions

added Tcl
(added Tcl)
Line 1,033:
30
</pre>
 
=={{header|Tcl}}==
Thw below script will merge an arbitrary number of files (which must be already sorted) specified on the command-line.
 
A careful reader will notice that '''$peeks''' is treated alternately as a dictionary ('''dict set''', '''dict get''') and as a list ('''lsort''', '''lassign'''), exploiting the fact that dictionaries are simply lists of even length. For large dictionaries this would not be recommended, as it causes [https://wiki.tcl.tk/3033 "shimmering"], but in this example the impact is too small to matter.
 
<lang Tcl>#!/usr/bin/env tclsh
proc merge {args} {
set peeks {}
foreach chan $args {
if {[gets $chan peek] > 0} {
dict set peeks $chan $peek
}
}
set peeks [lsort -stride 2 -index 1 $peeks]
while {[dict size $peeks]} {
set peeks [lassign $peeks chan peek]
puts $peek
if {[gets $chan peek] > 0} {
dict set peeks $chan $peek
set peeks [lsort -stride 2 -index 1 $peeks]
}
}
}
 
merge {*}[lmap f $::argv {open $f r}]
</lang>
 
== {{header|UNIX Shell}} ==
Anonymous user