http://qs321.pair.com?node_id=885049


in reply to scope and declaration in local packages

It's not a scope problem. The problem is that «Animal::Hog->sound();» comes before «my $sound1 = "knor1";» and «our $sound2 = "knor2";». You're basically inlining a module, but you're not properly emulating «use». To do so, use

BEGIN { package Animal::Hog; ... $INC{'Animal/Hog.pm'} = __FILE__; }

In this case, you can avoid doing the last statement. Simply adding «BEGIN» would do the trick.

Replies are listed 'Best First'.
Re^2: scope and declaration in local packages
by december (Pilgrim) on Jan 31, 2011 at 13:42 UTC

    I realised that I could use a BEGIN block, but I was basically wondering why Perl didn't complain about the functions, yet did so with the variables.

      So you think the function exists and the variable doesn't exist? That's not the case. The function and the variables are all declared at compile time. It's not complaining about the variables not existing. It's complaining that you didn't put a value in them, and that's because you didn't execute the assignment.

      my $sound1 = "knor1";

      is the same as

      my $sound1; $sound1 = "knor1";

      Many language have a special declaration syntax that allows for the initialisation of variables, but Perl does not. my always initialise the variable it creates to undef* (scalars) or empty (arrays and hashes). If you want it to have another value, you need to assign a value to it.

      * — Implementation differs slightly, but you're not suppose to ever encounter that.