do - block that returns a value, load a script
You can use do to create a block that returns the last evaluated value for block syntax. For string syntax, you can specify the name of the file and load the script.
# do block-a block that returns the last value do {...}; # do string-load script do $file_name;
Note that the block syntax and the string syntax have completely different functions. Let's take a closer look at each syntax.
Block that returns the last value - do block
You can use the do block to create a block that returns the last evaluated value.
# do block my $value = do { 1; 2; 3; };
If you write as above, 3 will be returned and 3 will be assigned to $value.
There is no particular reason to use this syntax when programming normally, but it is customary to use this syntax if you want to read the contents of a file all at once.
Read the contents of the file at once
The following description allows you to read all the contents of a file at once.
my $content = do {local $/; <$fh>};
A detailed explanation of this description is given below.
local is explained in "local - temporarily save and restore a package variable".
Loading script - do string
You can use the do string syntax to read a file as Perl source code.
A common method is to write the configuration file in Perl and read it.
Write the configuration file in Perl
It is convenient to write the configuration file in Perl.
my $conf_file = "app.conf"; my $conf = do $conf_file or die qq/Can't load config file "$conf_file":$! $@/;
The contents of the configuration file.
{ name =>'Foo', number => 9 }
If the file is not read or parsed successfully, the undefined value will be returned. If the file name does not exist, $! Will be set, and if the Perl source code fails to load, $@will be set to the error content.
The configuration file can be written in XML or JSON, but it's easiest to write in Perl.
The do string syntax should only be used to load a script that describes the settings. If you want to load the module, use use or require ..