Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I've done this before, so i must be missing something simple.

I have the following module, "test.pm":
#!/usr/bin/perl -w use strict; our $foo = "test"; 1;

and have the following script:
#!/usr/bin/perl -w use strict; use lib "/var/www/scripts"; use test; print $test::foo ."\n";

And get an "Use of uninitialized value in print" error. I've also tried using the following, which results in error as well:
print $foo

I can replace "foo" with any variable that does not exist and get the same error. So it seems like it is not reading test.pm properly. But it is at least finding it (trying to load a module that does not exist results in an error).

what am i doing wrong?

Replies are listed 'Best First'.
Re: Variables from modules
by dave_the_m (Monsignor) on Sep 16, 2004 at 14:05 UTC
    You need to add package test; at the top of test.pm

    Dave.

      That didn't do it either. I'm still getting the same error. test.pm now looks like this:
      package vars; use strict; our $foo = "test"; 1;
        er.
        package test;
        was thinking of something else while typing.
Re: Variables from modules
by sintadil (Pilgrim) on Sep 16, 2004 at 14:03 UTC
    Did you perhaps forget to put a package declaration in test.pm?
Re: Variables from modules
by zejames (Hermit) on Sep 16, 2004 at 14:33 UTC
    our declares a variable to be valid within the block or file.

    Use this code instead :

    package Test; use strict; use vars qw/$foo/; $foo = "test"; 1;


    update : as dave_the_m and ikegami have just said below, I was wrong. our can be used for that. So : code testing is good should be my new motto...

    --
    zejames
      our declares a variable to be valid within the block or file.
      Er, no. our creates a lexically-scoped alias of a global variable. The variable is still accessible from any src file by providing the fully-qualified name. There is is no need for the the OP to use use vars, as my working code I posted earlier demonstrates.

      Dave.

      Nope. our makes it so you don't have to use a fully qualified name when addressing the variable within the block or file. You can still access the variable from anywhere, because you never have to declare package variables (or whatever you call variables that aren't lexicals). I've tested it with our and it works great.