in reply to Simple question about foreach and my.

Well, you should always declare your variables using the appropriate mechanism (usually my) or otherwise your script won't run under use strict.

The choice is not, therefore, between using or not using my, rather where's the best place to put the my. You can either do

foreach my $var (@array)

or

my $var; foreach $var (@array)

The first has the advantage that the scope of the variable is restricted to your foreach loop and in the second example the variable scope is the scope that contains the loop. However, the first syntax was introduced relatively recently (5.005 or thereabouts), so if you are running on older versions of Perl (and you shouldn't be) then you'll be forced to use the second method.

--
<http://www.dave.org.uk>

"Perl makes the fun jobs fun
and the boring jobs bearable" - me

Replies are listed 'Best First'.
Re (tilly) 2: Simple question about foreach and my.
by tilly (Archbishop) on Mar 27, 2001 at 19:24 UTC
    I believe that 5.004 introduced it.

    In older Perl's I write like this:

    foreach (@array) { my $var = $_; # ... }
    which keeps the loop variable private. (At the cost of opening yourself up to wiping out your array if you call something that walks over $_ unexpectedly.)
Re: Re: Simple question about foreach and my.
by voyager (Friar) on Mar 27, 2001 at 20:25 UTC
    What about variables used within the loops (style, speed, etc.). Do you prefer:
    foreach my $var (@array) { my $other_var = .... etc. }
    or
    my $other_var; foreach my $var (@array) { $other_var = .... etc. }

      Depends completely on what I'm going to do with the variable. The overriding principle is that a variable is scoped as tightly as possible.

      If the variable is only used within the loop then it should be restricted to within the loop. If I'm going to use it outside the loop then I'll declare it outside the loop.

      --
      <http://www.dave.org.uk>

      "Perl makes the fun jobs fun
      and the boring jobs bearable" - me