# Warnings, strict and our aren't needed if you don't
# want to bother. I Just like to have them
use strict;
use warnings;
our $c = 5;
sub foo {
print $c;
}
# Next line is the only thing that's different from
# what you'd have if you were going to use "do"
# A filed being required/used should return something true
1;
And then use that as:
use Foo();
use strict;
# you couldn't call foo without () under use strict
# if you had used "require" or "do"
foo;
our $c;
print $c;
Notice the () in use Foo(). It
avoids a call to import, though supposedly if you use this you won't have a Foo package and there will be no import there, so you could leave them out too.
Having said that, it's still often a good idea to make commonly used code into a real module. You can use the Exporter if you want subs and variables in there available unqualified in your main code. It's only a few trivial lines more:
package Foo; # This line is new
use strict;
use warnings;
use base qw(Exporter); # This line is new
our @EXPORT_OK =qw($c foo); # This line is new, stuff the caller MAY
+import to use it unqualified
our $c = 5;
sub foo {
print $c;
}
1;
And on use you have to say which of the exported things you'd like to use:
# Next line is different, explicitely say we want to use foo unqualifi
+ed (without Foo::)
use Foo qw(foo);
use strict;
foo;
# We could also have listed $c in the import list and then use plain $
+c
# But let's instead show you can still access it by qualifying
print $Foo::c;
|