Featured post
perl - How I reference hash inside of subroutine? -
i trying use tie function of module config::inifiles cannot figure out how reference hash inside of sub routine. if remove tie function , related code sub routine works perfectly.
this line thought work, tells me "$cfg" not initialized.
use config::inifiles sub config_file {     $cfg_file = 'settings.ini';     %cfg;     tie %cfg, 'config::inifiles', ( -file => "$cfg_file" );      #my $cfg = config::inifiles->new( -file => $cfg_file );  }  sub esx_host_check {     $esx_host = config_file()->$cfg{esx}{host}; } i sure simple, stumped.
first off, tie function returns internal hidden object represents tie, , not tied variable itself.  secondly, can not return plural tied value (hash or array) subroutine , have work way expecting.  need return reference plural value, , dereference when need use it.
use config::inifiles;  sub config_file {     tie %cfg, 'config::inifiles', -file => 'settings.ini';  # tie variable     return \%cfg;  # return reference tied variable }  sub esx_host_check {     $esx_host = config_file()->{esx}{host}; # call sub , dereference value } if going use config hash more few times, best build , cache result:
{my $cfg; sub config_file {     tie %$cfg, 'config::inifiles', -file => 'settings.ini' unless $cfg;     return $cfg; }} this little different above.  first, setup config_file closure around private variable $cfg.  note scalar , not hash.  in sub, check see if variable has been initialized, , if not, call tie.  tie passed first argument of %$cfg dereferences undefined value hash, has effect of storing tied hash reference $cfg.
while little more complicated, technique need build config hash once, potentially saving lot of time.
- Get link
- X
- Other Apps
Comments
Post a Comment