xavier8854 has asked for the wisdom of the Perl Monks concerning the following question:

Hello, monks,

Here is the problematic code of my CGI
#!/usr/bin/perl -w use strict; use File::Basename; use CGI; use CGI::Carp; use Config::Tiny; chdir dirname($0); my $config = Config::Tiny->read('Config.ini'); croak "Cant read Config.ini" unless $config; .....

This works perfectly in debugger, even from shell, and generates the Web page as expected.

But at runtime in Apache, despite chdir dirname($0), it misearbly croaks

Sure, it is a current directory problem, but what did I miss ?

Thanx in advance, Xav

PS : as a new user, a short introduction : Im a senior IT engineer (systems, networks). Preferred OS FreeBSD. 57 yo, from France

Replies are listed 'Best First'.
Re: Config::Tiny croaks at runtime, not in debugger
by haukex (Archbishop) on May 06, 2016 at 15:12 UTC

    Hi xavier8854,

    Welcome!

    What is the exact error message, including the contents of $Config::Tiny::errstr?

    Also, I don't think chdir dirname($0); will be reliable in all environments, have a look at FindBin instead of trying to chdir (which may fail due to security/permission restrictions) or use $0 (which isn't always the name of the script file!). Even FindBin isn't always perfect but it tries fairly hard and has almost always worked for me.

    use CGI::Carp qw/fatalsToBrowser/; use FindBin; use File::Spec::Functions qw/catfile/; use Config::Tiny; my $config = Config::Tiny->read(catfile($FindBin::Bin,'Config.ini')); croak "Failed to read Config.ini: $Config::Tiny::errstr" unless $confi +g;

    Although you may want to consider the security implications of saving the config file alongside the script, and reporting the exact location of that file via the error message in case opening the file fails.

    Regards,
    -- Hauke D

Re: Config::Tiny croaks at runtime, not in debugger
by xavier8854 (Novice) on May 17, 2016 at 17:35 UTC

    Thanks hawkex, and sorry for the delay (I wasn't at the office these days)

    Apparently the problem is automagically fixed by downloading the CGIs to the FreeBSD destination host. It works as expected.

    Probably I should blame Apple's implementation of Apache and/or CGI, since my dev server is MacOSX.

    Cheers,

    Xav

      I really recommend reading haukex's post again and taking his advice to heart. Besides security concerns, changing directories in code is, to me, code smell. Lots of Perl devs, including me, work on OS X and it doesn't seem to have any more gotchas than any other *nix. And like any other *nix, I highly recommend against tampering with the System perl. That includes installing new modules. Plain Perl will likely be fine but once you mess with the wrong C-based module/lib, you may hose your entire installation. perlbrew and local::lib are a couple of ways to make it easier to have it all.