in reply to Reading Variables from a File
Here's what I use in my scripts. Say you have a text file named "config.txt" that looks like this:
# This is my configuration file variable1=111 variable2=222
I put this sub into my script to read that data back in:
sub GetSetting { my ($cfg_value,$cfg_filename,$cfg_default)=@_; open(CFGFILE,"<$cfg_filename") or die "Can't open configuration file $ +cfg_filename."; my @cf=<CFGFILE>; foreach $cfg_line (@cf) { if (index($cfg_line,"#")==0) { next; } # Lines starting with a hash ma +rk are comments my @ln=split("=",$cfg_line); if ($ln[0] =~ /$cfg_value/i) { chomp $ln[1]; return $ln[1]; } } close CFGFILE; return $cfg_default; # Return default if we can't find the value }
You set the default value when you call the sub. To read the setting back in, just do like so:
my $setting = GetSetting('variable1','config.txt','111');
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Answer: Reading Variables from a File
by Anonymous Monk on Jun 01, 2003 at 01:19 UTC | |
by #include (Curate) on Jun 02, 2003 at 09:00 UTC |