Choosing The Right Server-Side Scripting Language
By
Craig McElwee
2004-01-06
Task 5: File Reading
Again, opening a file to read is trivial in the scripting languages, and requires object instantiation on the part of Java. Actually reading from the file is somewhat different in each and highlights some philosophical differences between the languages. Perl and Python make it easy to read entire files, assigning each line to an element of an array or list, as appropriate, and then processing by iterating over each element. The others are better suited to reading a line, processing it, and then looking for another line. Here are examples from the least amount of code to the most (within reason and without idioms). In each case, the filehandle is 'in' and each line is printed to STDOUT:
Perl:
@lines = <IN>;
foreach $line (@lines){
print $line;
}
|
Note: Before Python programmers write to me saying Perl uses an extra character, note that I could have written "for" instead of "foreach", or even written the whole thing as: for (<IN>){ print }.
Python:
lines = in.readlines()
for line in lines:
print line
|
PHP:
while (!feof($in)) {
$line = fgets($in, 4096);
print $line;
}
|
Tcl:
while {1} {
gets $in line
puts $line
if {$line == ""} {
break
}
}
|
Java:
do {
try {
line = in.readLine();
if (line != null){
out.println(line);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
|
First published by IBM developerWorks
|
|
|
1 Votes |
|
|
|
|
You might also want to check these out:
|
Leave a Comment on "Choosing The Right Server-Side Scripting Language"
You must be
logged in to post a comment.
Link to This Tutorial Page!