in reply to Re^2: Syntax error - "my" within foreach loop
in thread Syntax error - "my" within foreach loop

It's not wrong because it's in a loop, but because you're accessing a hash element.

my declares a new, lexical variable. But you don't want to declare a new variable, you're accessing an item in an existing data structure.

  • Comment on Re^3: Syntax error - "my" within foreach loop

Replies are listed 'Best First'.
Re^4: Syntax error - "my" within foreach loop
by Klammer (Acolyte) on Apr 13, 2008 at 19:41 UTC
    OK, I see. But if I don't declare %count with my %count% the hash isn't an existing data structure, isn't it? Do I always have to declare a hash prior to using it within the foreach loop, or is there a way to do it all in one step within the loop? Sorry if this sounds stupid. ;)
      But if I don't declare %count with my %count% the hash isn't an existing data structure, isn't it?

      That's correct (except that it's my %count;, but that's probably just a typo).

      Do I always have to declare a hash prior to using it within the foreach loop, or is there a way to do it all in one step within the loop? Sorry if this sounds stupid. ;)

      You have to declare any variable that you use, if it's in a for loop or not.

      If you want to declare multiple variables in one rush, you can do it like so:

      my (%count, @items, $other_stuff, $more_stuff);

      When you get used to it doesn't feel stupid any more to declare variables before you use them ;-)

      If you declare a my variable inside a loop, it is only visible inside the loop. So if you wrote:

      for my $word (@words){ my %count; # WRONG $count{$word}++; }
      that would create a variable %count for each iteration, and loose its scope when the iteration finishes.