Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Answer: Reading Variables from a File

( #262054=categorized answer: print w/ replies, xml ) Need Help??

Q&A > input and output > Reading Variables from a File contributed by #include

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');

Comment on Answer: Reading Variables from a File
Select or Download Code
Replies are listed 'Best First'.
Re: Answer: Reading Variables from a File
by Anonymous Monk on Jun 01, 2003 at 01:19 UTC

    I would submit that it is often better to read all the configuration information at once. Here's a snippet that uses this philosophy:

    use strict; my(%config) = ("variable1" => "default1", "variable2" => "default2"); &get_settings("myconfig",\%config); sub get_settings{ my($filename,$config_hash) = @_; my($var,$val); return unless ref $config_hash eq "HASH"; open(CFGFILE,"<$filename") or die "Cannot open config file $filename: $!"; while (<CFGFILE>){ chomp; next if /^#/; ($var,$val) = split(/=/,$_,2); $config_hash->{$var} = $val if exists $config_hash->{$var}; } close(CFGFILE); }

    Of course, there's always Config::General, but it's probably overkill and you may not be able to count on it being there for you.

      Part of the reason why I like to grab settings "on the fly" is because you can then change those settings at runtime. By grabbing the setting only when I need it, I can tweak the configuration file while the script is running. For settings that can't be changed while running, I load them in at the beginning of the script and store them in scalars.

      A genius writes code an idiot can understand, while an idiot writes code the compiler can't understand.
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (17)
As of 2015-07-28 18:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (258 votes), past polls