CS 3723
  Programming Languages  
  Python versus Perl  

[This example adapted from "The Quick Python Book", by Ceder.]


Python versus Perl: Here the two languages duke it out with a similar simple application: coordinate-wise addition of two vectors. (I didn't write the Perl function.) This comparison is not entirely fair, but still . . .

Coordinate-wise addition of two vectors
Python Function Perl Function
# psum.py: cordinatewise sum of vectors
def pairwise_sum(x, y): # assume same length
    result = [] 
    for i in range(len(x)): 
        result.append(x[i] + y[i]) 
    return result
# psum.pl: cordinatewise sum of vectors
sub pairwise_sum {    # assume same length
    my ($x, $y) = @_; # copy array refs
    my @result;
    for (my $i=0; $i < @$x; $i++) {
      $result[$i] = $x->[$i] + $y->[$i];
    }
    return @result;
}
Added Python code Added Perl code
a = range(3,7)
b = range(8,12)
c = pairwise_sum(a, b)
print c
@a = (3..6);
@b = (8..11);
@c = pairwise_sum(\@a, \@b);
print "@c\n";
Output
% python psum.py -tt
[11, 13, 15, 17]
% perl psum.pl
11 13 15 17

(Revision date: 2014-06-05. Please use ISO 8601, the International Standard.)