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

C++
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.

Perl
open(INFILE, "in.txt") || die 'Couldn't open "in.txt"';
while(<INFILE>)
{
  ... 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 $_.

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

Reads like pseudocode.