Bill
Bill

Reputation: 1247

What the best way to handle project level variables in perl

I was asked to look into switching a bunch of ksh scripts into perl. Right now all the system variables are exported from a common file (urls, database usernames, etc).

My question is in perl what is the best way to handle these variables?

PS. I like the idea of using a ini file but then I need a ini file reading library (which people here wont like).

Upvotes: 1

Views: 97

Answers (3)

Borodin
Borodin

Reputation: 126742

To expand on my comment, here is an example config module MyConfig.pm that exports two constants.

package MyConfig;

use strict;
use warnings;

use base 'Exporter';

our @EXPORT = ( qw/ URL USERNAME / );

use constant URL => 'http:/domain.com/';
use constant USERNAME => 'myuser';

1;

and a program file that uses it

use strict;
use warnings;

use MyConfig;

print URL, "\n";
print USERNAME, "\n";

output

http:/domain.com/
myuser

If you read the documentation on Exporter you will see how to use @EXPORT_OK and %EXPORT_TAGS to categorize the constants and avoid polluting the calling package's namespace too much.

Upvotes: 3

jmcneirney
jmcneirney

Reputation: 1384

You could use a config file and read it in whenever you need.

use Config::Merge;

my $config = Config::Merge->new ( '/path/to/config_file.yml' );

my $file = $config->C('filename');

That will read in a yaml config file which will result in the yaml structure being available as a perl hash.

The yaml file could be something like:

db:
  name: db_name
  url : 192.168.1.1 

Back in the file:

print $file->{db}{name}  would print out 'db_name'.

Upvotes: 0

Sodved
Sodved

Reputation: 8608

I would use a similar concept to what your ksh scripts have.

Create a common package file with all the settings in them as package our variables. e.g. ProjConfig.pm contains

package ProjConfig;

use strict;
use warnings;

our $BaseUrl = 'http://www.fred.com/';
our $DbName = 'TheDB';

1;

Then your calling code simply refers to these variables with a qualified name. e.g. program.pl contains

#!/usr/bin/perl

use strict;
use warnings;

use ProjConfig;

{
    my $db = someConnectFunction( $ProjConfig::DbName );
    # do stuff
}

Upvotes: 0

Related Questions