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

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. ;)

Replies are listed 'Best First'.
Re^5: Syntax error - "my" within foreach loop
by moritz (Cardinal) on Apr 13, 2008 at 19:49 UTC
    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.