[perl-python] 20050116 defining a function

Xah Lee xah at xahlee.org
Sun Jan 16 09:45:53 EST 2005


© # 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)
©
© # 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.  Also, the string
© # immediately following the function
© # definition is the function's
© # documentation.
©
© # the unusual syntax of a.insert() is
© # what's known as Object Oriented syntax style.
©
© # try writing a factorial function.
©
© -------------------
© # the equivalent perl version is this:
©
© =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;
© my @result;
© my ($a, $b);
©
© sub fib($) {
©     my $n= @_[0];
©     @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.
© # see Òperldoc -t perlpodÓ
© # note: the empty line around it
© # is necessary, at least in perl version
© # 5.6 up to ~2002.
©
© # the Òuse strict;Ó is to make perl's
© # loose syntax stricter by enforcement.
© # Its use is encouraged by
© # perl gurus, but not all standard
© # packages use it.
©
© # the ÒmyÓ are used to declare variables.
© # necessary under Òuse strict;Ó
© # see Òperldoc -t 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.
© # see Òperldoc perlsubÓ for ref.
©
© # the @_[0] is the first element of the
© # array @_. The @_ array is a predefined
© # array, holding arguments to subroutines.
© # see Òperldoc -t perlvarÒ
©
© # see
© # perldoc -tf unshift
© # perldoc -tf pop
©
© # the last line, [fib(5)], is basically
© # to make it a memory address of a copy of
© # the list returned by fib(5), so that
© # Dumper can print it.
© # see Òperldoc -t perldataÓ or perlref
© # for unix-styled technicalities.
©
©  Xah
©  xah at xahlee.org
©  http://xahlee.org/PageTwo_dir/more.html




More information about the Python-list mailing list