[Melbourne-pm] Using strict...

Jacinta Richardson jarich at perltraining.com.au
Mon Feb 19 20:28:58 PST 2007

Tim Hunt wrote:

> I am updating *old* cgi-bin scripts to _use strict_.

You are very brave.  ;)  Did you notice that you're using the two argument
version of "open" without specifying file mode?  Depending on how the program
gets the config file name, that could be a security problem.

> The original author had a suite of config files A.cfg, B.cfg etc. that
> were parsed at run time to declare variables.

How many of these are there?  How many variables are they declaring?

> Of course, with strict on, this does not work as the variables are all
> confined  to the scope of the eval(config_line).

Yup that's correct.

> My options seem to be to declare all the variables in the main script
> and carry on regardless, or implement a better config method. 

If you know what variables you expect to import this shouldn't be too much of a
problem.  I presume you're happy to find out what these variables should be.

	# a.cfg
	use strict;

	our $foo = 'hello world';
	our $bar = 3;

	# main
	use strict;
	while (<IN>){
	   if ($@){
	our ($foo, $bar);         # Only change

	print $foo;

Personally I'd recommend using a better config method.  I usually use
Config::General but there are lots of other alternatives:

	# aa.cfg
	foo = hello world
	bar = 3

	#Main script:
	use strict;
	use Config::General;

	my $config_file = 'aa.cfg';
	my %config = Config::General->new($config_file)->getall();
	print $config{foo}, "\n";
	# or
	my $foo = $config{foo};

The above has a number of advantages over your original:

	* it's shorter (less places for bugs to hide),
	* can handle fields with multiple values
	* can handle flags
	* doesn't require explicit file handling (less problems with open)
	* should be easier for people to immediately understand
	* avoids sneaky security problems if your untaint() method isn't
	  perfect and bad people can edit your config files

On the downsides I don't believe that Config::General comes standard with Perl,
but I could be mistaken.

All the best,


   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
 (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |

More information about the Melbourne-pm mailing list