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

String Character Access

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: See if the first character in a string is 'H'. Assume the string is the contents of a line you are reading from a file in a loop.

Comment on this topic

C++
if(line[0] == 'H')
{
  ...

Basic C++ stuff.

Perl
if(substr($_, 0, 1) eq 'H')
{
  ...

Once again we see the Perl magic variable $_, which contains the line read from the file. Note there is no simple subscript operator for strings, one has to use the substr function. Note also that when comparing strings (unlike when comparing numbers), you have to use eq and not ==.

Python
if line[0] == 'H':
  ...

or

if line.startswith('H'):
  ...

The first form is natural for a C++ programmer. And you have the option of making it more English with endswith.