Choosing The Right Server-Side Scripting Language
By Craig McElwee
2004-01-06
Reader Rating:

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
If you found this article interesting, you may want to read these as well:
» Protecting your PHP and HTML Source Code
» Publishing Newsletters Using PHP & MySQL - 4
» Publishing Newsletters Using PHP & MySQL - 3
» Publishing Newsletter Using PHP & MySQL - 2
» Publishing Newsletters Using PHP & MySQL
» Unix Webserver Crontab Basics
|