Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: For and foreach...

by salvadors (Pilgrim)
on Jan 20, 2001 at 16:28 UTC ( [id://53233]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to For and foreach...
in thread difference between for and foreach?

Perl has these two statements for a reason and they are appropriate each in different cases ... is done far more easily (and efficiently?) with foreach.

No, no, no. For and foreach are identical. Yes, they're there for a reason, but that's not because they do anything different, or because one is better at one thing, or anything like that.

Perl as a language grew out of linguistic principles. Larry describes Perl as a diagonal language rather than an orthogonal one. It has no problem having more than one command that does exactly the same thing, just as most natural languages have words that mean exactly the same thing. The two different versions of for make it easier to read Perl in English.

You can quite happily, to take your examples, write:

foreach ($i=0; $i <= (scalar(@array)-1); ++$i) { ++$array[$i]; }
and
for $bar (@bar) { ++$bar; }
and perl will Do The Right Thing(tm). In fact it will Do The Same Thing. But many people will find it easier to read them the original way. Which is important in the Perl World.

Tony

Replies are listed 'Best First'.
(jeffa) Re: Re: For and foreach...
by jeffa (Bishop) on Jan 20, 2001 at 21:06 UTC
    and don't forget:
    for my $i (0..$#array) { ++$array[$i]; }
    for those times when you need the index
    much cleaner than doing it C-style.

    Jeff

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    F--F--F--F--F--F--F--F--
    (the triplet paradiddle)
    

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://53233]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.