Python/C++ vs. Perl/C++

File Iteration

Here's a little exercise that should demonstrate that Python is a more natural scripting language option for C/C++ programmers (and human beings in general) than Perl. This is but one of many possible examples.

The task: write a code snippet that opens a text file named "in.txt" and iterates through the file's lines in a loop, to operate on each line.

Comment on this topic

ifstream infile("in.txt");
const int MAX_LINE_LEN = 256;
char line[MAX_LINE_LEN];
while(infile.getline(line, MAX_LINE_LEN))
  ... do something with line

Somewhat messy due to the need for a buffer to hold the line.

open(INFILE, "in.txt") || die 'Couldn't open "in.txt"';
  ... do something with $_

The open call is straightfoward, but somewhat uglied up by the die clause. The while loop is a bit odd. The braces around the file handle INFILE combined with the while loop read each line into the built-in Perl variable $_.

infile = open("in.txt")
for line in infile:
  ... do something with line

Reads like pseudocode.