Read a file line by line: Difference between revisions

Content added Content deleted
(Add Brat solution)
(added perl)
Line 19: Line 19:
}</lang>
}</lang>
The File is managed by reference count, and it gets closed when it gets out of scope or it changes. The 'line' is a char[] (with newline), so if you need a string you have to idup it.
The File is managed by reference count, and it gets closed when it gets out of scope or it changes. The 'line' is a char[] (with newline), so if you need a string you have to idup it.

=={{header|Perl}}==
For the simple case of iterating over the lines of a file you can do:
<lang perl>open(FOO, '<', 'foobar.txt') or die $!;
while (<FOO>) { # each line is stored in $_, with terminating newline
chomp; # chomp, short for chomp($_), removes the terminating newline
process($_);
}
close(FOO);</lang>
The angle bracket operator <code>< ></code> reads a filehandle line by line. (The angle bracket operator can also be used to open and read from files that match a specific pattern, by putting the pattern in the brackets.)

Without specifying the variable that each line should be put into, it automatically puts it into <code>$_</code>, which is also conveniently the default argument for many Perl functions. If you wanted to use your own variable, you can do something like this:
<lang perl>open(FOO, '<', 'foobar.txt') or die $!;
while (my $line = <FOO>) {
chomp($line);
process($_);
}
close(FOO);</lang>

The special use of the angle bracket operator with nothing inside, will read from all files whose names were specified on the command line:
<lang perl>while (<>) {
chomp;
process($_);
}</lang>


=={{header|Python}}==
=={{header|Python}}==
Line 25: Line 49:
for line in f:
for line in f:
process(line)</lang>
process(line)</lang>
The with statement ensures the correct closing of the file after it is processsed, and iterating over the file object <code>f</code>, adjusts what is considered line separator character(s) so the code will work on multiple operating systems such as Windows, Mac, and Solaris without change.
The with statement ensures the correct closing of the file after it is processed, and iterating over the file object <code>f</code>, adjusts what is considered line separator character(s) so the code will work on multiple operating systems such as Windows, Mac, and Solaris without change.


Python also has the [http://docs.python.org/library/fileinput.html fileinput module]. This can process multiple files parsed from the command line and can be set to modify files 'in-place'.
Python also has the [http://docs.python.org/library/fileinput.html fileinput module]. This can process multiple files parsed from the command line and can be set to modify files 'in-place'.