Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

for, foreach: any difference?

by muba (Priest)
on Apr 02, 2004 at 16:48 UTC ( [id://342028]=perlquestion: print w/replies, xml ) Need Help??

muba has asked for the wisdom of the Perl Monks concerning the following question:

I sometimes see a for loop which I would have written as a foreach myself, and vice versa.
Also, a little while ago I concluded that -MO=Deparse turned my for into a foreach (or was it the other way around? Well, whatever :) ), providing the same 'arguments'.

So... is there actually any difference between for and foreach?

Replies are listed 'Best First'.
Re: for, foreach: any difference?
by Limbic~Region (Chancellor) on Apr 02, 2004 at 17:20 UTC
    MUBA,
    Ok - yes and no - depends on how you look at it. One is usually referred to as a C-style for loop (does not localize $_ or implicitly alias looping variable) and the other is typically referred to as a foreach loop (which does both of those things).
    for ( $i = 0; $i < 10; $i++ ) { # C-style but could also say foreach } foreach ( @array ) { # Localizes $_ and implicitly aliases looping variable # Could also just be for }
    In your code, it does not matter which name you use. It is the looping construct that follows the name that determines the internal behavior.

    Cheers - L~R

Re: for, foreach: any difference?
by saberworks (Curate) on Apr 02, 2004 at 17:09 UTC
    Camel Book, 3rd Edition, page 118 says, "The foreach keyword is just a synonym for the for keyword, so you can use for and foreach interchangeably, whichever you think is more readable in a given situation." So you could do:
    #!/usr/bin/perl use strict; my @array = qw(one two three four); print "Foreach:\n"; foreach my $item (@array) { print "$item\n"; } print "\nFor:\n"; for my $item (@array) { print "$item\n"; }
    Same thing...
Re: for, foreach: any difference?
by waswas-fng (Curate) on Apr 02, 2004 at 16:59 UTC
    Check out for, this has been discussed many times before -- get to know super search.


    -Waswas
Re: for, foreach: any difference?
by borisz (Canon) on Apr 02, 2004 at 17:06 UTC
    for and foreach are the same.
    Boris
•Re: for, foreach: any difference?
by merlyn (Sage) on Apr 02, 2004 at 21:45 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://342028]
Front-paged by diotalevi
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2024-04-26 08:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found