You already have good answers to your immediate question, but there are some slightly deeper issues to consider too. But first, it is great to see that you are using strictures (strict and warnings) in the first place - many Perl beginners don't.
Some languages (C and Pascal for example) require that all variables be declared in a block before any other statements. That often means the declaration is a long way from the first use and it can be hard to be sure where the first use is. Perl on the other hand allows you to declare variables pretty much anywhere you want to. That means that you can mostly declare a variable the first place it is used and assign a value to it as part of the declaration. This is a Good Thing&tm; because it makes it easier to see where and how the variable is used.
A more subtle thing is that inside a block (a loop body for example) you get a new "instance" (fresh sheet of paper to write the value on) every time the program flow enters the block and the variable in most cases can't be accessed outside the block.
There are many other things that you will learn about variables in Perl over time including closures and that the loop variable for a for loop is an alias and doesn't persist outside the loop. Enjoy your new adventure. ;)
In reply to Re: Syntax error - "my" within foreach loop
by GrandFather
in thread Syntax error - "my" within foreach loop
by Klammer
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |