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

Reference Passing

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 that passes a list into a function such that the function can modify the passed list (and not just a copy of the list).

Comment on this topic

C++
void addItem(vector<string>& theList)
{
  theList.push_back("xyz");
}

vector<string> aList;
aList.push_back("abc");
addItem(aList);

This would be pass-by-reference in C++. After the call to addItem, the aList will contain two strings: "abc" and "xyz".

Perl
sub addItem
{
  my $listRef = shift;

  push(@$listRef, 'xyz');
}

my @aList = ('abc');
addItem(\@aList);

Note the required use of many punctuation symbols. This is to accomplish a pass-by-reference. It's actually fairly similar to the C++ (or more likely C) if we were to pass-by-pointer there. You have to pass the list into addItem by reference, using a backslash to indicate this in the function call. Then the function has to know it is receiving a reference, which is a scalar (hence the $listRef). The scalar reference must be coerced into its actual type, which is a list, by prepending the @ to the reference in the call to push. Once you learn all these requirements, it becomes fairly easy to write this type of thing. But if you take a step back and take a long gander at what is written, you should realize that it's pretty ugly. And the first few attempts at this can be very frustrating.

Python
def addItem(theList):
  theList.append('xyz')

aList = ['abc']
addItem(aList)

Everything is passed by reference in Python, so no special handling is required.