Version: v0.8.1 - Beta.  We welcome contributors & feedback.

File.readEachLine

$file.readEachLine($lineFunction, $options={}) -> any

Description

Read a file one line at a time.

This is recommended for potentially large files, as it is more memory-efficient than reading the entire file at once.

For each line, $lineFunction will be called, which receives the line (without a newline character) as its only argument.

By default, it will skip over lines that are empty or have only whitespace characters.

// Count the number of inspirational quotes
$numProgrammingQuotes = 0

$quoteFile = file'files:/quotes.txt'

$quoteFile.readEachLine(fun ($line) {
    if $line.contains('programming', -ignoreCase) {
        $numProgrammingQuotes += 1
    }
})
Early Return

If $lineFunction returns a non-null value, it will stop reading the rest of the file and return that value.

If all lines are read without halting, it will return null.

$bookFile = file'files:/book.txt'

// Find the first line that has "THT"
$thtLine = $bookFile.readEachLine(fun ($line) {
    if $line.contains('THT') {
        return $line
    }
})

print($thtLine)
//= Ex: 'THT makes my hair look full and radiant!'

Options

Option Value Description
keepBlanks true/false Do not skip blank lines.
file'files:/data.txt'.readEachLine(fun ($line) {

    // ...

}, -keepBlanks)

See Also