To do something to each element of an array, you need a loop over each element of the array. I don't know what's special about for loops that they need to be avoided. Maybe if you told us that, we could help you better.
I wouldn't use a for loop anyway. I'd use a counting loop. The syntax of a counting loop is much simpler than that of a for loop, it's faster do to the much smaller number of opcodes, and it also uses a constant amount of memory. (Mostly for the first reason. The other two are bonuses.)
Counting loop (an optimised form of foreach loop):
$a[$_] -= $b[$_] for 0..$#a;
Foreach loop:
$a[$_] -= $b[$_] for (),0..$#a;
Using map like a foreach loop:
map { $a[$_] -= $b[$_] } 0..$#a;
while loop:
my $i = @a; $a[$i] -= $b[$i] while $i--;
Goto loop:
my $i = @a;
goto CHECK;
BODY: $a[$i] -= $b[$i];
CHECK: goto BODY if $i--;
Recursion loop:
sub subarray {
my ($a, $b) = @_;
local *_helper = sub {
my $i = $_[0];
return if !$i--;
$a->[$i] -= $b->[$i];
_helper($i);
};
_helper(0+@$a);
}
subarray(\@a, \@b);
Recursion loop, take 2:
sub subarray {
my ($a, $b) = @_;
local *_helper = sub {
return if !@_;
$_[0] -= $_[-1];
shift; pop;
&_helper;
};
_helper(@$a, reverse(@$b));
}
subarray(\@a, \@b);
pairwise loop:
use List::MoreUtils qw( pairwise );
@a = pairwise { $a - $b } @a, @b;
Update: Added more alternatives :)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.