Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Reading Variables from a File

by Voytek (Initiate)
on Dec 29, 2001 at 10:38 UTC ( #135082=categorized question: print w/replies, xml ) Need Help??
Contributed by Voytek on Dec 29, 2001 at 10:38 UTC
Q&A  > input and output


Hey! I looked through the site, and I couldn't really find this. What I would like to do is have Perl (in CGI, I don't know if this makes a difference - I don't think it would) create a file with some variables in it... I know how to do this. But in the future, how can I open this file again and get the different numbers in it to become certain variables? Thanks a lot, Voytek

Answer: Reading Variables from a File
contributed by Kanji

See Object Serialization Basics for a few pointers, but it might be easier to use's (alt.) own save() and restore_paramaters() functions, along with your open() and flock()s.


Answer: Reading Variables from a File
contributed by Chrisf

Say you have written the numbers to the file and have delimited them with | so the data in the file looks like this:


You can then read them into your variables like so:

#!/usr/bin/perl -w use strict; # declare your variables my $varFile = "variables.txt"; my ($var1,$var2,$var3); # open the file open DATA, $varFile or die "Can't open file: $!"; while (<DATA>) { # chomp the line chomp; # split the line into values and assign them to your variables ($var1,$var2,$var3) = split /\|/; } # close the file close DATA;

The length of the code can be reduced substantially, but this gives you an idea of what's going on.

Answer: Reading Variables from a File
contributed by gav^

use Storable; store \%hash, 'data'; $hr = retrieve 'data';
Answer: Reading Variables from a File
contributed by msemtd

I quite often provide Perl apps compiled into executables with perl2exe for deployment on systems without Perl installed. As such I always provide a back-door means by which the configuration can be adjusted e.g.: -

use strict; my $cake = 'chocolate'; my $pie = 'apple'; eval slurp("");
Which will run at run time assuming a nice handy slurp function is provided to read a file...
## slurp - read a file into a scalar or list sub slurp { my $file = shift; local *F; open F, "< $file" or die "Error opening '$file' for read: $!"; if(not wantarray){ local $/ = undef; my $string = <F>; close F; return $string; } local $/ = ""; my @a = <F>; close F; return @a; }
So when contains...
$pie = 'pecan'; cake = 'fairy';
...the pie and cake get set to your favourites rather than the defaults.

If you are interested in errors from the eval, it can be followed by something like...

if($@){ print "Some errors happened...\n\n"; print $@."\n\n"; print "Oh well...\n"; }
Answer: 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');
Answer: Reading Variables from a File
contributed by Anonymous Monk

Depending on how you output the data, it could be read back by using a require (or preferably eval).

# save stuff
print FILE '$myvar = ' . $myvar . ";\n";

then to red back, just eval() the file input, or require. You may also consider Data::Dumper, which takes more complex structures and converts them into strings which can be eval()'ed to retrieve the data again.

Of course, this may not be what you're looking for in a CGI environment, as this data file would have to be writable by 'nobody'... don't want to eval it if you're not sure ;)

another option would be this:

# saving
print FILE "myvar = $myvar\n";
print FILE "anothervar = $anothervar\n";

# retrieving
while (<FILE>) {
  if (/^(\w+) *= *(.+)$/) {
     ${$1} = $2;

This is assuming anothervar and myvar are not multi-line strings. This is a little safer than a blind eval(), although it involves symbolic scalar references...

Please (register and) log in if you wish to add an answer

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

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

    How do I use this? | Other CB clients
    Other Users?
    Others meditating upon the Monastery: (4)
    As of 2020-09-19 13:05 GMT
    Find Nodes?
      Voting Booth?
      If at first I donít succeed, I Ö

      Results (114 votes). Check out past polls.