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 :)


In reply to Re: compare arrays numbers by ikegami
in thread compare arrays numbers by nicholaspr

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.