Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2024-04-18 17:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found