my variables in foreach loops 
Author Message
 my variables in foreach loops

How does perl handle the memory for the my var in this statment



   print "$var";

Quote:
}

The reasion I ask is my boss has a phobia about using the my keyword in
foreach loops.

He is under the impression that the my variable will have its memory
alocated and dealocated through each ittaration of the loop.

Is he correct.

If not is there any documentation to disprove his claim.



Sun, 11 Apr 2004 22:10:16 GMT  
 my variables in foreach loops


Hi John,

| How does perl handle the memory for the my var in this statment
|


|    print "$var";
| }

I can't exactly tell you how it does that, but what exactly does it matter
to your use of foreach?

| The reasion I ask is my boss has a phobia about using the my keyword in
| foreach loops.

Why?
See the quote below for a description of what my does. If you weren't using
my, the difference would be that it's not lexically scoped. Maybe research
on that'll be easier for you. :)

| He is under the impression that the my variable will have its memory
| alocated and dealocated through each ittaration of the loop.

I doubt it a lot, but what bad would it do anyway?

| Is he correct.
|
| If not is there any documentation to disprove his claim.

from perlsyn:

Foreach Loops
The foreach loop iterates over a normal list value and sets the variable VAR
to be each element of the list in turn. If the variable is preceded with the
keyword my, then it is lexically scoped, and is therefore visible only
within the loop. Otherwise, the variable is implicitly local to the loop and
regains its former value upon exiting the loop. If the variable was
previously declared with my, it uses that variable instead of the global
one, but it's still localized to the loop.
The foreach keyword is actually a synonym for the for keyword, so you can
use foreach for readability or for for brevity. (Or because the Bourne shell
is more familiar to you than csh, so writing for comes more naturally.) If
VAR is omitted, $_ is set to each value.

HTH,
Steffen
--
$_=q;33352987319029872958319011313364356732192639127636833335345138283712




Mon, 12 Apr 2004 04:21:33 GMT  
 my variables in foreach loops

Quote:

> How does perl handle the memory for the my var in this statment



>    print "$var";
> }

It creates a variable lexically scoped to the loop. It's just shorthand
for this:

{
   my $var;

      print $var;
   }

Quote:
}

because Perl Hackers are Lazy (in the good way).

Quote:
> The reasion I ask is my boss has a phobia about using the my
> keyword in foreach loops.

He shouldn't. The syntax was modified (in 5.005, I think) to allow this
very thing. It's a good thing.

Quote:
> He is under the impression that the my variable will have its
> memory alocated and dealocated through each ittaration of the
> loop.

> Is he correct.

No, the guys over at P5P are smarter than that. :) Memory will be
allocated the first time the loop is encounted (and reallocated if
additional space is needed). Perl will not release the memory until the
program finishes, but it will reuse it if scope returns to the loop.

Quote:
> If not is there any documentation to disprove his claim.

As far as the details of the memory allocation? I don't believe so,
unless he wants to read the source. :) There is an entry about foreach()
loops in perlfunc, and my() is discussed in perlsub, but these talk more
about behavior than implementation.

In general, memory management is something you neither can nor should be
concerned about in Perl.

-mjc



Mon, 12 Apr 2004 05:22:58 GMT  
 my variables in foreach loops
Quote:

>How does perl handle the memory for the my var in this statment



>   print "$var";
>}

>The reasion I ask is my boss has a phobia about using the my keyword in
>foreach loops.

I find the best way to deal with these kinds of phobias is to write up a
little test script with the Benchmark module and see if his way is any
faster than your way.  If the benchmark doesn't show a big difference,
then does it really matter whether he is right or not?

Quote:
>He is under the impression that the my variable will have its memory
>alocated and dealocated through each ittaration of the loop.

>Is he correct.

>If not is there any documentation to disprove his claim.

--
Jason S Kohles



Mon, 12 Apr 2004 04:15:49 GMT  
 my variables in foreach loops
[Posted and mailed]



Quote:
> If not is there any documentation to disprove his claim.

The typical boss-with-a-phobia wouldn't believe documentation anyway.

One pragmatic way is to compare the outputs of:

        perl -Dm -e 'for my $i (0..99) { }'

and

        perl -Dm -e 'for my $i (0..10) { }'

And see if memory is allocated differently between the two examples.  
(It's not.)

--
    Clinton A. Pierce            Teach Yourself Perl in 24 Hours  *and*

"If you rush a Miracle Man,     for details, see http://geeksalad.org    
        you get rotten Miracles." --Miracle Max, The Princess Bride



Mon, 12 Apr 2004 05:30:42 GMT  
 my variables in foreach loops

Quote:

> How does perl handle the memory for the my var in this statment



>    print "$var";
> }

> He is under the impression that the my variable will have its memory
> alocated and dealocated through each ittaration of the loop.

No, absolutely not.  That my variable is outside the loop!
But more importantly, on each iteration of the loop, the variable
is actually an alias to each of the values in the list.

I suspect that what your boss is concerned about is a my variable
*inside* the loop, like this:

  for ( ... ) {
    my $var = ...;

But even here, perl knows that the variable is likely to be needed
repeatedly, so it doesn't reallocate, it reuses.  Just one of those
sneaky optimizations that perl performs under the hood.

--
John Porter

Somebody set up us the bomb!!!



Mon, 12 Apr 2004 04:42:20 GMT  
 my variables in foreach loops
Quote:

>> The reasion I ask is my boss has a phobia about using the my
>> keyword in foreach loops.

> He shouldn't. The syntax was modified (in 5.005, I think) to allow this
> very thing. It's a good thing.

I know this. Which is why I use it. However proving it to my PHB is a
diffrent matter :-)


Mon, 12 Apr 2004 17:11:17 GMT  
 my variables in foreach loops
Thank you for all your help. Now all I have to do is find the memory
alocation stuff in the source code and get my boss to understand it ;-)

Oh well at least *I* know that im doing the right thing TM



Mon, 12 Apr 2004 17:17:46 GMT  
 my variables in foreach loops

Quote:
> No, absolutely not.  That my variable is outside the loop!
> But more importantly, on each iteration of the loop, the variable
> is actually an alias to each of the values in the list.

Or is it?  My boss had a similar phobia, this was my code snippet that
convinced him it was going to be ok.

$ perl -e 'for my $var (1 .. 3) { print \$var . "\n" } print \$var;'
SCALAR(0x1a7f09c)
SCALAR(0x1a7f09c)
SCALAR(0x1a7f09c)
SCALAR(0x1a72f84)

So the $var inside the loop has the same memory location each time, but the
one outside has a new address.  This won't run under strict because the last
$var is being created for me as a package variable.

Peter C.



Tue, 13 Apr 2004 01:30:13 GMT  
 my variables in foreach loops

Quote:

> Thank you for all your help. Now all I have to do is find the
> memory alocation stuff in the source code and get my boss to
> understand it ;-)

Yikes. I hope you're kidding. How about a counter-example?

#!/usr/bin/perl -w
use strict;

foreach my $var (0 .. 10) {
    print \$var, "\n";

Quote:
}

__END__
SCALAR(0x1b9ef64)
SCALAR(0x1b9ef64)
SCALAR(0x1b9ef64)
SCALAR(0x1b9ef64)
SCALAR(0x1b9ef64)
SCALAR(0x1b9ef64)
SCALAR(0x1b9ef64)
SCALAR(0x1b9ef64)
SCALAR(0x1b9ef64)
SCALAR(0x1b9ef64)
SCALAR(0x1b9ef64)

Admittedly that doesn't really *prove* that memory wasn't reallocated.
But if it was (even though we know it wasn't) it ended up in the same
place. Maybe that's proof enough for an irrationally phobic boss.

-mjc



Tue, 13 Apr 2004 01:49:19 GMT  
 my variables in foreach loops

Quote:

> The reasion I ask is my boss has a phobia about using the my keyword in
> foreach loops.

> He is under the impression that the my variable will have its memory
> alocated and dealocated through each ittaration of the loop.

        My signature quote these days is "Unecessary efficiency is the root of
all bad engineering".  This is a perfect example.  If speed is so
critical that something like this is a concern, then you have chosen the
wrong language for implementation.  Perl is many things - fast is not
one (I'm talking about mission critical, real time fast here - the only
situation in which it is reasonable to be fretting over where the
variables get instantiated).  But I notice you didn't mention whether
the program runs fast enough, which I interpret to mean that it does.

        My advice: just declare the {*filter*}y thing at the top of the block - it's a
no-change.  You seem to need to prove yourself right (or at least not
wrong) , and far be it from me to get between you and your boss, but
life might just get a little easier if you accept your boss's
"mentoring" and let him/her "contribute" to the project.  Not all issues
are technical...

        Of course, if you already know that you're tusslin' with the boss, then
roll up them sleeves and dive into that source code!

/|/|ike



Tue, 13 Apr 2004 06:10:40 GMT  
 my variables in foreach loops
Folks,

As far as I understand the situation, we are comparing
apples with oranges here.

If you do:

for my $var (1..10000000)
{
  print \$var, "\n";

Quote:
}

then the reason you see the same location is that Perl
performs yet *another* optimization, (which was
added sometime during Perl 5's life but I can't remember
when w/o looking it up), which is that the range is
*not* allocated in any memory since Perl
knows it is being used essentially as a loop counter.

If however you do:



{
  print \$var, "\n";

Quote:
}

then Perl (obviously) allocates the whole space for the
list and then (obviously) when $var is aliased to each of the
elements taking a reference to it is taking a reference to
a different location each time.

That *doesn't* of necessity mean that $var itself is being
reallocated, just that it is aliasing a different location
each time.

Try the above. Be prepared for a loooooonnnggg wait for the second
to even start running, since, it has to allocate all that
space first, (it may not even have enough VM to do it if you
don't have much memory, - so, - be prepared for your Perl session
to either give you an out of memory error or to freeze your session
depending upon operating system.)

If you try the *first* example, then it begins running almost
instantly since Perl makes the optimization I mentioned above
and uses a counter, (at a single location), hence the same memory
address.

Note: I've given you fair warning above that the example that
allocates the list may hang your machine. Do not blame me if you
try it and it crashes if you don't have enough VM. Backup first.

8-)

Kind regards

Derek Jones. (Perl course author.)


Quote:

> > No, absolutely not.  That my variable is outside the loop!
> > But more importantly, on each iteration of the loop, the variable
> > is actually an alias to each of the values in the list.

> Or is it?  My boss had a similar phobia, this was my code snippet
> that
> convinced him it was going to be ok.

> $ perl -e 'for my $var (1 .. 3) { print \$var . "\n" } print
> \$var;'
> SCALAR(0x1a7f09c)
> SCALAR(0x1a7f09c)
> SCALAR(0x1a7f09c)
> SCALAR(0x1a72f84)

> So the $var inside the loop has the same memory location each time,
> but the
> one outside has a new address.  This won't run under strict because
> the last
> $var is being created for me as a package variable.

> Peter C.

=====
------------------------------------------------------
Derek Jones                      1051, Bollinger Road,
Tel:    717 359 8817                      Littlestown,
Mobile: 717 977 4556                    PA, 17340, USA

AIM:   scunacc

__________________________________________________
Do You Yahoo!?
Make a great connection at Yahoo! Personals.
http://personals.yahoo.com



Tue, 13 Apr 2004 07:57:41 GMT  
 my variables in foreach loops

Quote:
>     My advice: just declare the {*filter*}y thing at the top of the block -
> it's a no-change.  You seem to need to prove yourself right (or at least
> not wrong) , and far be it from me to get between you and your boss, but
> life might just get a little easier if you accept your boss's
> "mentoring" and let him/her "contribute" to the project.  Not all issues
> are technical...

>     Of course, if you already know that you're tusslin' with the boss,
> then roll up them sleeves and dive into that source code!

This is actualy one battle I can afford to loose, so maybe the politic
thing would be to bow out gracefully ;-)


Tue, 13 Apr 2004 19:00:03 GMT  
 
 [ 13 post ] 

 Relevant Pages 

1. allowed index variables in foreach loops

2. special variable for foreach loops?

3. save mutiple writeln's into an array

4. MS Access memo fields

5. How to Summary & Append Double Record

6. foreach loop variable localizing

7. Variable evaluation in foreach / for loops??

8. References in foreach loop variable

9. global my() variable used in foreach() loop loses its value

10. Splice in foreach loop, then quit loop: legal?

11. foreach loop works, for loop not

12. Save output from foreach loop outside loop?

 

 
Powered by phpBB® Forum Software