MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1＆1

# Python ＆ Perl: Defining A Function

Xah Lee,

## Python

The following is a example of defining a function in Python.

```def fib(n):
"""This prints n terms of a sequence
where each term is the sum of previous two,
starting with terms 1 and 1."""
result=[];a=1;b=1
for i in range(n):
result.append(b)
a,b=b,a+b;
result.insert(0,1)
del result[-1]
return result

print fib(6)
```

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

Note the use of 「.insert」 to insert 1 at the beginning of a list, and 「del result[-1]」 to remove the last element in a list.

The unusual syntax of 「a.insert()」 is what's known as Object Oriented syntax style.

Try writing a factorial function.

## Perl

Here's a line-by-line equivalent Perl version:

```
=pod

fib(n) prints n terms of a sequence where each
term is the sum of previous two,
starting with terms 1 and 1.

=cut

use strict;

sub fib(\$) {
my \$n= \$_[0];

my @result;
my (\$a, \$b);
@result=();\$a=1;\$b=1;
for my \$i (1..\$n){
push @result, \$b;
(\$a,\$b)=(\$b,\$a+\$b);
}
unshift @result, 1;
pop @result;
return @result;
}

use Data::Dumper;
print Dumper [fib(5)];
```

The 「=pod」 and 「=cut」 is Perl's way of demarking inline documentation called POD. Note: the empty line around it is necessary, at least in Perl version up to 5.6 (in wide use around ≈2002).

perldoc perlpod

The 「use strict;」 is to make Perl's loose syntax stricter thru compiler enforcement. Its use is encouraged by Perl gurus, but not all standard packages use it.

If you declare 「use strict;」, then you need to declare your variables. Example: 「my \$n;」.

perldoc strict

The \$ in fib(\$) is there to declare that fib has a parameter of one scalar. Its use is however optional and uncommon. It is used for clarity but has also met with controversy by Perl gurus as being unperl.

perldoc perlsub

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

The last line 「[fib(5)]」, is basically to make it a memory address of a copy of the list returned by fib(5). This is needed because the function 「Dumper」 takes a reference.