Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Reading Variables from a File

by Voytek (Initiate)
on Dec 29, 2001 at 10:38 UTC ( [id://135082]=perlquestion: print w/replies, xml ) Need Help??

Voytek has asked for the wisdom of the Perl Monks concerning the following question: (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

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: Reading Variables from a File
by Kanji (Parson) on Dec 29, 2001 at 11:26 UTC

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

      --k.


Re: Reading Variables from a File
by Chrisf (Friar) on Dec 30, 2001 at 01:15 UTC
    Say you have written the numbers to the file and have delimited them with | so the data in the file looks like this:

    1111|2222|3333

    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.

Re: Reading Variables from a File
by gav^ (Curate) on Dec 30, 2001 at 01:56 UTC
    use Storable; store \%hash, 'data'; $hr = retrieve 'data';
Re: Reading Variables from a File
by msemtd (Scribe) on May 30, 2003 at 18:48 UTC
    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("config.pl");
    Which will run config.pl 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 config.pl 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"; }
Re: Reading Variables from a File
by #include (Curate) on May 31, 2003 at 10:15 UTC

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

      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.
Re: Reading Variables from a File
by Anonymous Monk on Jan 10, 2002 at 11:14 UTC
    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...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://135082]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2024-04-23 11:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found