� # 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
�  [EMAIL PROTECTED]
�  http://xahlee.org/PageTwo_dir/more.html

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to