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

Length

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 code to get the length of an array and a string.

Comment on this topic

C++
vector<string> list;
...
vector<string>::size_type length = list.size();
...
if(list.size() > 0)
{
  ...
string str;
...
string::size_type strLength = str.size();

We're assuming use of the STL here, and we're showing the use of the length in different contexts (assigning to a local variable, using in a comparison). Note that whether getting the length of a string or of a vector, we use a consistent approach.

Perl
my @list;
...
my $length = scalar(@list);
...
my $anotherWayToGetLength = $#list + 1;
...
if(@list > 0)
{
  ...
my $str;
...
my $strLength = length($str);

OK, as usual, there are several ways to accomplish this in Perl, none of them being too intuitive. You can "scalarize" the array, which turns it into the length of the array. This is done with the explicit call to scalar. You can also use the $# operator (?) which returns the index of the last element in the array, so you have to remember to add 1 to get the array length. Or, if you need to use the length in an arithmetic expression, simply using the array name, as in the if statement above, will replace the array name with the length of the array.

Now, to get the length of a string, we actually use the built-in function length. This makes good sense and is readable! But you cannot use length on an array!

Python
aList = []
...
length = len(aList)
...
if len(aList) > 0:
  ...
str = ''
...
strLength = len(str)

Python, much like C++, uses the same mechanism to find the length of various data types, the built-in function len.