Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: For and foreach...

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


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 21, 2001 at 02: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
Chatterbox?
and the web crawler heard nothing...

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

    No recent polls found