Reputation: 121
I am learning Perl.
I saw a script using function "do" on a file. Then i read that about that function :
If do can read the file but cannot compile it, it returns undef and sets an error message in $@ . If do cannot read the file, it returns undef and sets $! to the error. Always check $@ first, as compilation could fail in a way that also sets $! . If the file is successfully compiled, do returns the value of the last expression evaluated.
Inclusion of library modules is better done with the use and require operators, which also do automatic error checking and raise an exception if there's a problem.
You might like to use do to read in a program configuration file. Manual error checking can be done this way: You might like to use do to read in a program configuration file. Manual error checking can be done this way:
# read in config files: system first, then user for $file ("/share/prog/defaults.rc", "$ENV{HOME}/.someprogrc") { unless ($return = do $file) { warn "couldn't parse $file: $@" if $@; warn "couldn't do $file: $!" unless defined $return; warn "couldn't run $file" unless $return; } }
I don't understand why they are talking about compiling a config file? What kind of config file it is? Why/When do we use that config file ?
Thanks
Upvotes: 2
Views: 1729
Reputation: 57600
Sometimes, a script is used in place of a configuration file. This can then set up global state, or return some value. For example:
myprogrc
:
{
foo => "bar",
baz => 42,
}
Usage:
my $file = "myprogrc";
if (my $config = do $file) {
# do something with the config values
print "config values were $config->{foo} and $config->{baz}\n";
}
else {
warn "couldn't parse $file: $@" if $@;
warn "couldn't do $file: $!" unless defined $config;
warn "couldn't run $file" unless $config;
}
Don't do this. Because the config file is just Perl code, it could execute arbitrary stuff – dangerous! E.g. an `rm -rf ~`
would be a nasty surprise.
There are many better config formats:
and if it really has to be, you could use JSON or XML. All of these formats have the advantage that they are just data, not code. They are therefore safe to use (assuming the parsers don't have bugs).
Upvotes: 8