Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-18 00:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found