Hey fellow monks,

I have a question about scope in packages and I hope somebody smarter and with deeper knowledge of Perl internals can explain the resulting error messages to me.

Given the following simplified code:

#!/usr/bin/perl -wT use warnings; use strict; # call object method Animal::Hog->sound(); # here we define the object { package Animal::Hog; my $sound1 = "knor1"; our $sound2 = "knor2"; sub new() { my $this = shift; my $class = ref($this) || $this; my $self = {}; bless $self; return $self; } sub sound() { my $self = shift; print $sound1, "\n"; print $sound2, "\n"; return 'knor'; } }

... I get this result:

Use of uninitialized value $sound1 in print at ./tmp.pl line 30. Use of uninitialized value $Animal::Hog::sound2 in print at ./tmp.pl l +ine 31.

I am wondering why Perl knows about Animal::Hog->sound() without predeclaring it, yet returns an error for the lexical variables $sound1 and $sound2. It confuses me because I expect Perl to either have parsed the section and declared the variables and functions, or for it to not have done so and hence not know about any variables or functions in that block at all.

Duh?

Thanks for any insight!



PS: I know I could move the package declaration above the invocation, use a BEGIN block or declare the objects in another file.


In reply to scope and declaration in local packages by december

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.