Perl-Python Tutorial: Defining A Function

2005-01-16

Python

The following is a example of defining a function.

def myFun(x,y):
     """myFun returns x+y."""
     result = x+y
     return result

print myFun(3,4) # prints 7

A string immediately following the function definition is the function's documentation.

Optional Parameters

A function can have optional parameters. If no argument is given, a default value is assumed. To define optional parameters, use the form “optParam1 = defaultVal1, optParam2 = defaultVal2, ...”.

def myFun(x, y=1):
    """myFun returns x+y.
    Parameter y is optional and default to 1"""
    return x+y

print myFun(3)

Reference: Python Doc↗.

Perl

Here is a example of a function.

# MyFun(a,b) returns a+b
sub myFun {
  $a = $_[0]; # get first arg
  $b = $_[1]; # get second arg

  $result; # local var
  $result = $a + $b;

  return $result;
}

# calling the function
print myFun(3,4);

Note: Unlike most other languages, perl subroutine's parameters are not declared. If you write “sub myFun(a,b) {...}”, that'd be illegal syntax.

The “$_[0]” is the first element of the array “@_”. The “@_” array is a predefined array. It's values are the arguments passed to subroutine.

Optional Parameters

To define a function with optional parameters, just use “defined($_[n])” to check if the argument is given.

# MyFun(x,y) returns x+y. y is optional and default to 1.
sub myFun {
  $x = $_[0];

  if (defined $_[1]) {
    $y = $_[1];
  } else {
    $y = 1;
  }

  return $x+$y;
}

print myFun(3);

Reference: perldoc perlsub↗.


Page created: 2007-11.
© 2005 by Xah Lee.
Xah Signet