in reply to Re^4: Syntax error - "my" within foreach loop
in thread Syntax error - "my" within foreach loop
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:
that would create a variable %count for each iteration, and loose its scope when the iteration finishes.for my $word (@words){ my %count; # WRONG $count{$word}++; }
|
|---|