On 3/16/2012 17:25, Steven D'Aprano wrote:
On Fri, 16 Mar 2012 13:55:06 +0100, Kiuhnm wrote:
I don't understand the reason for $arg1 and $arg2. Is there some reason
why the code couldn't do this instead?
my(@list1, @list2) = @_;
@_ contains references to arrays. You can't pass two arrays to a
function.
Why ever not? That seems like basic functionality to me. I can't imagine
any modern language that lacks such a simple feature. Even Pascal allows
you to pass arrays as arguments to functions.
Is there some design principle that I'm missing that explains why Perl
lacks this feature?
Perl uses references only when explicitly told so.
For instance,
my @a = (1,2,3);
my @b = @a;
creates two distinct arrays and you can modify @b without touching @a at
all.
Another odd thing is that Perl "flattens" lists or arrays. If you write
my @a = (1,2,3);
my @b = (0,@a,4);
you'll end up with @b = (0,1,2,3,4).
If you want nested data structures, you'll need to use explicit references:
my @b = (0,\@a,4); # '\' = take the ref of
Now you can write
$b[1][0]
but that's short-hand for
$b[1]->[0] # deref. $b[1] and get the first elem
which is short-hand for
${$b[1]}[0]
Square brackets build an array and return a reference to it:
my $ref = [0,1,2];
(Notice that, in Perl, '$' means one ($ref is one reference), while '@'
means many.)
Now you can write
my @a = (1,[2,3,4],5)
because you're putting a reference into $a[1]!
So, let's go back to this code:
sub pairwise_sum {
my($arg1, $arg2) = @_;
my(@result) = ();
@list1 = @$arg1;
@list2 = @$arg2;
for($i=0; $i < length(@list1); $i++) {
push(@result, $list1[$i] + $list2[$i]);
}
return(\@result);
}
Here @list1 and @list2 are copies. No careful Perl programmer would do
such extra copies. And no Perl programmer would use a C-style for loop.
Kiuhnm
--
http://mail.python.org/mailman/listinfo/python-list