In general is considered a bad practice to import variables from an external file by using require or use.

  1. #!/usr/bin/perl
  2. package conf;
  3. $username = “diego”;
  1. #!/usr/bin/perl
  2. package main;
  3. require “conf.pl”;
  1. print “username: $usernamen;

The example above may work but is definitely a bad approach since conf.pl could be modified to inject and execute malicious code. In case you need to import configuration variables, the Config::General module is the way to go.

Leaving that aside, this script still works. The clause require imports everything from an external Perl file. Any global variable or function defined in conf.pl will be visible from main. It is like those variables where actually defined in main.pl. Bear in mind that conf.pl is not a package but a Perl file, so there is no need to add a namespace when referring to their variables from main.

require can be useful for splitting our source code in several files. When those files have something in common, or rather say, provide a new functionality to our program, then a module is preferred. The clause use is in general used when importing new modules.

However, mixing up require and use clauses can lead to unexpected behaviours in our program. Consider this new package:

  1. #!/usr/bin/perl
  2. package MyPackage;
  3. require “conf.pl”;
  1. #!/user/bin/perl
  2. package main;
  3. use MyPackage;
  4. require “conf.pl”;
  5. print “username: $usernamen;

The result of executing main.pl returns nothing. Why? As it was mentioned before, requiring an external file from a package has the same effect as declaring all the global variables and functions of the required file as if they were first declared in the package which import them. That means, in the example above, that $username now is in the context of MyPackage, and refering to $username from main has no effect. We should instead refer to it as $MyPackage::username.

The bottom line here is not to import configuration variables by using require or use. Use the Config::General module in that case.