Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

lsort

Status
Not open for further replies.

bebig

Technical User
Oct 21, 2004
111
US
this time, I am learning about lsort.
test.txt file

10:00
12:00
15:00
20:00
02:00

this is a code for sort. but it does not work.
would you please tell me what the problem is?
thank you in advance.

set sortA [lsort -decreasing "$startTime"]
puts $sortA

===== here is a code========
set readFile [open "test.txt" "r"]

gets $readFile line

while {![eof $readFile]} {
set lineList [split $line ,]
set lineList1 [string map {\" ""} $line]
set lineLen [llength $lineList1]
set lenStartTime [expr {$lineList1 - 1}]
set lenRunTime [expr {$lineList1 - 3}]
set houseNum [lindex $lineList1 2]

set startTime [lindex $lineList1 $lenStartTime]
set runTime [lindex $lineList1 $lenRunTime]


set sortA [lsort -decreasing "$startTime"]
puts $sortA
#puts "$houseNum $startTime $runTime"

gets $readFile line

}
 
The "lsort" statement you have is working fine. You can verify this in a tclsh shell in the following way:


% set b [list 10:00 12:00 15:00 20:00 02:00]
10:00 12:00 15:00 20:00 02:00
% lsort -decreasing $b
20:00 15:00 12:00 10:00 02:00


Granted I don't know what the file you're reading contains, but it appears that the variable, startTime, is an element of a list, not a list. I say "appears" because a list element can be a list, itself. Your statement [blue]"set startTime [lindex $lineList1 $lenStartTime]"[/blue] implies to me that you won't be able to "lsort" on $startTime.

Here's another tip (even though you didn't ask). There is nothing whatsover wrong with your file reading while loop. However, I find it more concise and readable to read (at least smallish files) in one gulp and split the lines into a list at the same time:

set fileList [split [read $fid] \n]

Now, each line of the file (test.txt in this case) is an element of fileList. You can loop through each line (without a boolean test) with "foreach":

foreach line $fileList { ... }

Bob Rashkin
rrashkin@csc.com
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top