in reply to Read a static file from module directory

If you know the location of the config file relative to the script which uses your module, you can use FindBin:
# Parent script resides in /usr/local/myproject/bin # Module and config file reside in /usr/local/myproject/lib use FindBin qw($Bin); sub get_config { my $CONFIGPATH = "$Bin/../lib/acme.config"; open (CONFIG, "<$CONFIGPATH") or die "$0: File '$CONFIGPATH': $!"; undef $/; my $c=<CONFIG>; close CONFIG; return $c; }
A couple of other notes: <list>
  • You should get in the habit of explicitly directing your open() calls. E.g. use "<$CONFIGFILE" instead of "$CONFIGFILE". In this particular case it isn't a big deal, but if $CONFIGFILE was supplied by a user, that user could set it to something bad like "|rm -rf /*".
  • chomp() operates directly on the variable you give it as an argument, so returning chomp($c) won't do what you think it does.
  • chomp() doesn't do anything at all in slurp mode ($/ = undef) anyway. :)
  • </list>

    -Matt

    Replies are listed 'Best First'.
    Re: Re: Read a static file from module directory
    by l_millr (Initiate) on Nov 30, 2001 at 03:04 UTC
      My bad, perils of gut-and-paste. I already found out about chomp being an in-place method and not a result. Point taken on directing open, I will use that.

      Problem I have is that the calling script does not reside in /usr/local. It's in the httpd docs directory as a cgi script using CGI.pm. I do a 'require acme;' and then when I try to invoke get_config is when the sadness starts.

      I will look into FindBin, that seems promising.

      Thanks for the help, I will go forth and attempt to sin no more.