--- "Robin Lavallee (LMC)" <[EMAIL PROTECTED]> wrote:
> 
> Hi,
> 
>       I have a small conceptual problem. I have been 
> told that doing:
> 
> my $item;
> foreach $item (@arr) { ... }
> 
> is more efficient than:
> foreach my $item (@arr) { ... }
> 
> Because it does not reallocate memory each time. 

I doubt that matters enough to ever be an efficiency issue.
If it does, you might want to code that piece of your script in C....

> This means that the scope of $item in the second 
> example is actually after the { }. Right ?

That's right.
 
> Then can someone explains why the following code:
> 
> #---Begin Code---
> use strict;
> my $par="50";
> print "$par\n";
> 
> my @arr = ('first', 'second', 'third');
> foreach $par (@arr)
> {
>       print "$par\n";
> }
> print "$par\n";
> #---End Code-----
> 
> produces the following output:
> 50
> first
> second
> third
> 50

This I've never noticed. Frankly, I'd like an elaboration on that
myself. =o)
 
> This means that the $par in the foreach loop is 
> NOT the same as the $par outside of the loop. However, 
> I use strict and I do not even do a "my $par". How can 
> this be possible ?

$par in the foreach is aliased to each of the elements in @arr, so the
first time, $par *is* $arr[0], the next time is's $arr[1], etc. It's
literally the same variable, so it you change $par, you change @arr.

But I have no idea why it's set back to 50 afterwards.
I think I read it in the docs, but I don't remember where.
 
> However, when I use the print "\$par", I see that it
> allocates a different address on each iteration of
> the loop, even without the par. So what does on 
> anyway ?

that's taking a ref to $arr[0] the first time, then $arr[1], etc, so
the addresses will be different. Or at least that's what it seems to
me.

Any explanations I could offer beyond that are hypothetical and beyond
the scope of this list, so I leave it to one both more knowledgeable in
the matter and better able to explain such things in beginner's terms.

Volunteers?

__________________________________________________
Do You Yahoo!?
Get personalized email addresses from Yahoo! Mail - only $35 
a year!  http://personal.mail.yahoo.com/

Reply via email to