.
Developer Spot - Web Development Tutorials
 


Web Hosting Directory
Budget Web Hosting Linux Web Hosting Small Business Hosting
Windows Web Hosting Reseller Web Hosting Web Hosting Articles

Choosing The Right Server-Side Scripting Language

By Craig McElwee
2004-01-06
Reader Rating: 4 out of 5
Bookmark Print Version
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 (&lt;IN&gt;){ 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();
}
}





Article Pages:
How Five Languages Do The Same Basic Tasks
Task 1: Get and Format The Time/Date
Task 2: Put Form Field Data Into Variables
Task 3: Search and Replace
Task 4: File Writing
Task 5: File Reading
Task 6: Split Comma-Delimited Line Into Variables
So, Which One Should You Use?
Resources

First published by IBM developerWorks


 Rate this article:   Poor          Excellent 


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



 
Development Tutorials
ASP
CGI & Perl
CSS
HTML
Java
JavaScript
Linux
PHP
XML




More Resources
Web Hosting Articles
Development Tutorials: CGI & Perl - CSS - HTML - Java - JavaScript - Linux - PHP - XML