Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First off, the <code>tie</code> function returns the internal hidden object that represents the tie, and not the tied variable itself. Secondly, you can not return a plural tied value (hash or array) from a subroutine and have it work the way you are expecting. You need to return a reference to the plural value, and then dereference it when you need to use it.</p> <pre><code>use Config::IniFiles; sub config_file { tie my %cfg, 'Config::IniFiles', -file =&gt; 'settings.ini'; # tie variable return \%cfg; # return a reference to the tied variable } sub esx_host_check { my $esx_host = config_file()-&gt;{ESX}{host}; # call sub and dereference value } </code></pre> <p>If you are going to use the config hash more than a few times, its probably best to build it and then cache the result:</p> <pre><code>{my $cfg; sub config_file { tie %$cfg, 'Config::IniFiles', -file =&gt; 'settings.ini' unless $cfg; return $cfg; }} </code></pre> <p>This is a little different than above. First, we setup <code>config_file</code> to be a closure around the private variable <code>$cfg</code>. Note that it is a scalar and not a hash. Then in the sub, we check to see if the variable has been initialized, and if not, call <code>tie</code>. <code>tie</code> is passed a first argument of <code>%$cfg</code> which dereferences the undefined value as a hash, which has the effect of storing the tied hash reference into <code>$cfg</code>.</p> <p>While a little more complicated, this technique will only need to build the config hash once, potentially saving a lot of time.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload