views:

1560

answers:

2

Heylo,

I'm experiencing, somewhat of, a conundrum regarding perl script development. I have written a small Perl script using the standard (basic) Perl installation. I have the following setup:

C:\MyScript\perl.pl
C:\MyScript\configuration\config.ini
C:\MyScript\output\output.txt

This is the perl.pl source:

$config      = '/configuration/config.ini';
$conf        = Config::IniFiles->new( -file => $config_file );
$output_dir  = conf->val('output', 'out_dir');
$output_file = "$output_dir/output.txt";

open (out, ">$output_file") || die ("It's not your day mate!");
print out "This is a test...";
close out;

This is the config.ini contents:

[output]
output_dir = C:\MyScript\output

The problem I am having is that the second line ($conf) appears to be having trouble opening the file at that location. As I will be using this script in both a windows and unix environment (without installing any addition modules) I was wondering how I could get around this? What I was hoping was to create a script that would entirely configurable through the config.ini file. The config however, only works if I give it's absolute path, like so:

$config = 'C:\MyScript\configuration\config.ini';

But since this will be deployed to several diverse environments modifying the scripts source is out of the question. What would you guys recommend? How should one approach such a scenario?

Any help and/or advice is greatly appreciated.

All the best, MC

+3  A: 

The problem lies in the $config assignment line -

$config      = '/configuration/config.ini';

This searches for config.ini from the root directory due to the leading '/', interpreting the path as an absolute rather than relative. Try changing it to

$config      = './configuration/config.ini';

This though will only work if you execute the perl script from the 'MyScript' directory. Have a look at the FindBin module for such cases or you could manipulate the $0 variable to get your perl script path.

muteW
That worked great thanks!Except, I had to create a batch file and execute that on the scripts root. Running it from Perl Express didn't work.Problem solved none-the-less!Thanks!
+1  A: 

Here is a solution to allways know which is your current directory and use your other dirs

use strict;
use warnings;
use FindBin;
use File::Spec;
use Cwd;
BEGIN {
    $ENV{APP_ROOT} = Cwd::realpath(File::Spec->rel2abs($FindBin::Bin)) ;
}
#now you know your script directory, 
#no matter from where your script is called
#if you have Modules specific for your script which are in 
#a dir "lib" in the same dir as your script is
use lib  (
"$ENV{APP_ROOT}/lib",
);
my $config      = $ENV{APP_ROOT} . '/configuration/config.ini';
#Here is your script
#...
$output_file = "$ENV{APP_ROOT}/$output_dir/output.txt";

All Modules are from the CORE distribution so you have them installed. Note that Windows accepts "/" slashes, so you can use them there too.

Cheers.

Berov