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

Function Arguments

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 the function definition for a function (not a class method) named "func" that takes four int parameters, "parm1" - "parm4", and returns an int. The last parameter should be defaulted to 0.

Comment on this topic

int func(int parm1, int parm2, int parm3, int parm4 = 0);

Easy enough. We're just showing what's required in the header file here to note the mechanism for handling the default argument.

sub func
  my $parm1 = shift;
  my $parm2 = shift;
  my $parm3 = shift;
  die "Usage: func(parm1, parm2, parm3, parm4 = 0)"
    unless defined($parm3);
  my $parm4 = shift || 0;

OK, pretty strange looking if you aren't used to Perl. Or even if you are used to Perl. Frankly, it's a sloppy way to accomplish something pretty basic. Note the special code (die) to handle the case when not enough arguments are passed to the function. Perl doesn't care if you call this function with no arguments or with 10 arguments. Note also that this code does not handle the case of passing too many arguments, only too few. Note also the use of my to restrict the scope of the variables to the function. Variables are global by default in Perl. This method of parameter passing will undoubtedly be baffling to an experienced C/C++ programmer. There are other ways to retrieve named variables (equally as ugly, I might add), but this is the idiom in code I've seen that is written by experienced Perl programmers.

def func(parm1, parm2, parm3, parm4 = 0):

This handles an incorrect number of arguments (no extra code needed, Python enforces this, like C++) and the default argument. The named parameters have function scope.