foreachLineTcl 9.1 onlychannels
Runs a script one time for each line of a text file.
foreachLine VARNAME NAME BODY
Description
Opens the file NAME as text and runs BODY one time for each line, with the line and no newline in the variable VARNAME of the caller. BODY runs in the scope of the caller. An empty line is a line, and a last line with no newline is a line. An empty file runs BODY no time.
break in BODY ends the loop, and continue goes to the next line. The file closes at the end, also after break and after an error of BODY.
The command is in Tcl 9.1 only. A new interpreter has no foreachLine: the host turns on the capability channels.
Arguments
| Argument | Type | Default | Description |
|---|---|---|---|
| VARNAME | variable name | required | The variable for each line, in the scope of the caller. |
| NAME | path | required | The path of the file. |
| BODY | script | required | The script to run for each line. |
Returns
An empty string.
Examples
% writeFile l.txt "a\nb\n"; set n 0; foreachLine line l.txt {incr n}; set n
2
# The empty line is a line, and so is the last line with no newline.
% writeFile l.txt "a\n\nb"; set r {}; foreachLine line l.txt {lappend r "<$line>"}; set r
<a> <> <b>
% set r {}; foreachLine line l.txt {if {$line eq ""} continue; lappend r $line}; set r
a b
% set r {}; foreachLine line l.txt {lappend r $line; break}; set r
a
# BODY sees the local variables of the proc.
% proc count {name} {
> set n 0
> foreachLine line $name { incr n }
> return $n
> }
> count l.txt
3
# The file closes after the error.
% catch {foreachLine line l.txt {error stop}}; llength [file channels file*]
0
Errors
% foreachLine line l.txt {error "bad line"}
bad line
-errorcode NONE
% foreachLine line nope.txt {}
couldn't open "nope.txt": no such file or directory
-errorcode POSIX ENOENT {no such file or directory}
% foreachLine line l.txt
wrong # args: should be "foreachLine varName filename body"
-errorcode TCL WRONGARGS
Differences from Tcl
- In tclsh 9.1,
foreachLineis a proc. In ztcl it is a command, andinfo bodygives an error.
Facts
- Capability
channels. A new interpreter does not have it until the host turns it on.- Tcl release
- Tcl 9.1 only.
- Since
- ztcl 1.0.0-beta.3