Process arrays without copying even the return values
In the previous solution we passed the references to the function but returned a full array, thereby copying all the values. If we care about memory and speed we might eliminate this copying by returning the reference to the resulting array.
The cost is a small (?) inconvenience as now we have to dereference the resulting array reference in the calling code.
#!/usr/bin/env perl
use strict;
use warnings;
my @first = (2, 3);
my @second = (7, 8, 5);
my $res_ref = add(\@first, \@second);
print "@{ $res_ref }\n";
sub add {
my ($one_ref, $two_ref) = @_;
my @result;
foreach my $i (0..@{ $one_ref }-1) {
if (defined $two_ref->[$i]) {
push @result, $one_ref->[$i] + $two_ref->[$i];
}
else {
push @result, $one_ref->[$i];
}
}
foreach my $i (@{ $one_ref }..@{ $two_ref }-1) {
push @result, $two_ref->[$i];
}
my $ret = \@result;
return $ret;
}