0

What are the differences ( if any ) for me as the user of the package "Test::Test" between this two package-versions:

Test::Test;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(hello);
use strict; use warnings;

our $c = 3;
sub hello {
    print "$_\n" for 0 .. $c;
}  

.

Test::Test;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(hello);

$c = 3;
sub hello {
    print "$_\n" for 0 .. $c;
}
sid_com
  • 24,137
  • 26
  • 96
  • 187

3 Answers3

4

It's a good practice to always enable strict and warnings. These pragmas help you to catch many simple errors and typos.

These two samples are equivalent. But the first one is preferred, because it explicitly declares the global variable $c using our and enables strictures and warnings.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
3

FWIW, the proper way to write this module is like this:

package Test::Test;
use strict;
use warnings;

use Exporter 'import';  # gives you the import method directly
our @EXPORT = qw(hello);

my $c = 3;
sub hello {
    print "$_\n" for 0 .. $c;
}

See perldoc Exporter for the best practices on writing modules with exports, for various scenarios.

I would also suggest changing the name of this package, as the Test:: namespace is already in use by core modules and CPAN distributions.

Ether
  • 53,118
  • 13
  • 86
  • 159
1

Variables in perl are by default global, regardless of whether they are declared in a module or not. The "my", "local" and "our" keywords scope the variable in different ways. In your example, "our $c" restricts the visibility of the variable to your package (unless you chose to export it, but that's another story).

So, for your latter example, any other piece of code that access and modify $c will impact your code too.

See http://perldoc.perl.org/functions/our.html for the official documentation on the "our" keyword.

Kim Burgaard
  • 3,508
  • 18
  • 11
  • 6
    This isn't really accurate. `$c` is a package global (`$Test::Test::c`) with or without `our`, and anyone, within the package or not, can access it by that name. However with `strict 'vars'` enabled, you can't just call it `$c` even in `Test::Test`, unless an exception is made using `use vars` or a lexical alias is created using `our`. `my` and `local` of course do entirely different things. – hobbs Nov 10 '10 at 07:48
  • 3
    See also http://stackoverflow.com/questions/3626190/why-are-variables-declared-with-our-visible-across-files/3626333#3626333 for further explanation of exactly what `our` does, how it's different from `use vars`, and why it doesn't just mean "make it visible in this package". – hobbs Nov 10 '10 at 07:49
  • Right, it's the combination of "use strict" and "our" that is significant. Using strict forces the programmer to declare the variable and thus consider the scope. – Kim Burgaard Nov 10 '10 at 08:10