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


Perl is environmentally friendly - it saves trees

In reply to Re: Syntax error - "my" within foreach loop by GrandFather
in thread Syntax error - "my" within foreach loop by Klammer

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.