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

I have got the working code which read .cfg file where .cfg file contains an array @cfg and list of hash within it, And the script contain bit of code which read that array @cfg but I am having problem to understand how the reading process carries on bit lost and confuse. Subroutine which carries out reading process looks like this,
sub ReadCfg { my $file = $_[0]; our $err; { # Put config data into a separate namespace package CFG; # Process the contents of the config file my $rc = do($file); # Check for errors if ($@) { $::err = "ERROR: Failure compiling '$file' - $@"; } elsif (! defined($rc)) { $::err = "ERROR: Failure reading '$file' - $!"; } elsif (! $rc) { $::err = "ERROR: Failure processing '$file'"; } } return ($err); }
Can any one help me, please. Cheers

Replies are listed 'Best First'.
Re: Help me to understand code
by GrandFather (Saint) on Jul 13, 2009 at 00:20 UTC

    "my script"? You perhaps mean someone else's script that you have copied or are trying to understand?

    The key to understanding it is that do compiles the contents of file whos name is given in $file into the context of the executing code. That is likely to introduce new variables into the context of the executing code.

    The series of if statements check the outcome of the compilation process.

    Note that in general this is a very insecure technique for managing configuration. You would be much better to use something like YAML instead.


    True laziness is hard work
      I agree with Grandfather, compiling config statements as Perl executable statements is in general not a good idea. Another idea that I've used before is one of the modules like Config::INI::Reader, there are a number of .ini file type readers and writers.

      Basically the idea is to make what looks like a very simple DB query to get the value that you want. A typical .INI type file is short and these modules build a memory resident hash. Access is very performant. Sometimes I build a very "thin" layer on top of the CPAN module so I can ask a question like: IsValidCity('Houston'); or whatever.