Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use "use 5.12.0; use warnings;" in a perl module?

Tags:

module

perl

I am not sure if and what difference it makes if a start a perl module with

package MYPACKAGE;
use 5.12.0;
use warnings;

# functions are here

1;

or

use 5.12.0;
use warnings;
package MYPACKAGE;

#  functions are here

1;

or if these use ... are not regarded at all because the use ... are inherited from the calling perl script.

The question probably boils down to: is it worthwile to specify those use ... in a module or is it sufficient if I have them specified in my perl script.

like image 640
René Nyffenegger Avatar asked Apr 13 '13 11:04

René Nyffenegger


1 Answers

Pragmatic modules have lexical, not dynamic scope.

The version pragma activates certain features in the current scope, depending on the version. It doesn't activate these features globally. This is important for backwards-compability.

This means that a pragma can be activated outside of the module definition, but inside our scope:

# this is package main
use 5.012; # activates `say`
package Foo;
say "Hi"; # works, because lexical scope

This is different from normal imports that are imported into the current package (!= scope).

The warnings pragma activates warnings inside the current scope.

However, every file should contain the use strict, as lexical scope never stretches accross files. Pragmas are not transitive:

Foo.pm:

say "Hi";
1;

main.pl:

use 5.012;
require Foo;

fails.


Where exactly you put these pragmas is thus largely irrelevant. I'd recommend putting the pragmas before the package when you have multiple namespaces in the file, e.g.

use 5.012; use warnings;

package Foo;
...;
package Bar;
...;
1;

but to put the package first if it is the only one in the file.

package Foo;
use 5.012; use warnings;
...;
1;

The only important thing is that you do use them ;-)

like image 160
amon Avatar answered Oct 23 '22 05:10

amon