Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Can someone provide me an example of storing a perl variable to a file and reading it back?
my $myVar = "hello there"
open (FILE "> $filename" ) || die "the end is near!";
....please fill in....
example of how to read it back in would be appreciated.
Thank you,
HockeyHabit

Replies are listed 'Best First'.
Re: read/write perl variables to/from file
by TedYoung (Deacon) on Feb 14, 2005 at 22:38 UTC

    Hi, below I am using newlines to seperate variables. This is far from foolproof, but demonstrates what you asked for.

    open FILE, ">filename" or die $!; print FILE $myVar, "\n"; close FILE; #... later on... open FILE, "filename" or die $!; $myVal = <FILE>; chomp $myVal; #remove the newline close FILE;

    If you need to do more, look at Data::Dumper or Storable, both part of the core modules. They facilitate the serialization of complex data structures.

    Ted Young

    ($$<<$$=>$$<=>$$<=$$>>$$) always returns 1. :-)
Re: read/write perl variables to/from file
by m-rau (Scribe) on Feb 15, 2005 at 08:21 UTC
Re: read/write perl variables to/from file
by nedals (Deacon) on Feb 15, 2005 at 01:00 UTC
    These are probably to most used file read/write constructs.
    # Read the total content of a file. With or without '<' open(FIL,"<$filename") || die "Cannot open $filename for reading: $!"; my @data = <FIL>; close(FIL); # Read a file line by line. Again with or without '<' open(FIL,"<$filename") or die "Cannot open $filename for reading: $!"; while (my $data = <FILE>) { ## statements }; close(FIL); # Create a file and write a line of data. # NOTE: If the file already exists it will be OVERWRITTEN my $data = "A line of text"; open(FIL,">$filename") || die "Cannot create $filename for writing: $! +"; print FILE "$data\n"; close(FIL); # Append a line of data to a file. Creates the file if it does not exi +st. open(FIL,">>$filename") || die "Cannot open $filename for appending: $ +!"; print FILE "$data\n"; close(FIL);
Re: read/write perl variables to/from file
by K_M_McMahon (Hermit) on Feb 14, 2005 at 22:41 UTC
    after your code, insert this.
    print FILE $myVar; close(FILE); open (FILE,"<$filename") or die "I cannot open $filename to read.\n"; my @file_contents=<FILE>; close(FILE); print "$myVar should equal ".chomp($file_contents[0])."\n";

    -Kevin
    my $a='62696c6c77667269656e6440676d61696c2e636f6d'; while ($a=~m/(^.{2})/s) {print unpack('A',pack('H*',"$1"));$a=~s/^.{2}//s;}
Re: read/write perl variables to/from file
by Random_Walk (Prior) on Feb 15, 2005 at 14:57 UTC

    You may also want to look at Tie::File or dbmopen. The first links an array to a flat text file, the second will link a hash to a binary dbm file.

    Cheers,
    R.

    Pereant, qui ante nos nostra dixerunt!