Re^2: Interview Prepration
by merlyn (Sage) on Apr 04, 2005 at 17:36 UTC
|
| [reply] |
|
foreach ( my $i = 0; $i < 10 ; $i++ )
{
print "\$i is $i\n";
}
Is this a foreach loop?
for my $user (@names)
{
print "Found user $user\n";
}
| [reply] [d/l] [select] |
|
Yes, and yes. Spelled "f-o-r", pronounced "foreach". Spelled "f-o-r-e-a-c-h", pronounced "for".
If you start handwaving "for and foreach are the same" in front of people enough, they wonder why the variable "didn't localize in my for loop... I thought for did that!".
It really is important to distinguish the two kinds of loops, even though 90% of the time we write "for", we prounounce it "foreach".
| [reply] |
|
|
|
|
The difference between "for" and "foreach" is four characters of extra typing for the latter. Other than that they are the same. Because you apparently associate one of the words with a Perl-style loop and another with a C-style loop is not sufficient reason to say that "for" is different from "foreach". The words may have a different history, but their use in scripts is identical.
| [reply] |
|
That's a bit like saying the difference between George Bush and George W Bush is only the W. After all, you can use George Bush to refer to either one.
But they really are different people! They're not the same!
And that's the same with for/foreach. They are not the same! There's a for loop, and there's a foreach loop, and you can use the word "for" or "foreach" to refer to either one, but they are not the same.
| [reply] |
|
|
|
|
Your opinion has been noted. But perl doesn't care about your opinion, and will treat the keywords for and foreach to be the same. I'm just answering the interview questions - and I think that the interview is about probing my perl knowledge, and what I know about the opinion of some well known members of the Perl community.
| [reply] |
|
| [reply] [d/l] [select] |