Coder's Guild Mailing List

Re: Reading and writing PERL arrays

Posted by G.P.Gillis on 2000-04-08

AD - 

I am not exactly sure what you are looking for here but here is my interpretation.  From
what I see, when you modify the array element, you are not adding a CR/LF character to 
the end of the element before returning it to the array.  This effects your file format by 
effectively removing a dataline from the file and clumping the data together on a single line.

Here is some code ...

#!c:\perl\ -w

# PERL version 
# This is perl, version 5.005_02 built for MSWin32-x86-object

$index = 5; # Modify 6th element in array
$tmp   = 0;

# Always check if file opened OK.
open FILE, "file.dat" or die "Can not open file for input!\n";

# Read in array elements from file - remove CR/LF characters from each element.
chomp( @array = <FILE>);
close FILE;

# Get element from array and modify in some way ( incrementing here ).
$tmp = $array[$index];
printf( "Tmp is %s before modification\n", ( $tmp));
$tmp++;
printf( "Tmp is %s after modification\n", $tmp);
$array[$index] = $tmp;

# Save elements from array to file, adding CR/LF character to each element to
# maintain file format.
open FILE, "+> file.dat" or die "Can not open file for output!\n";
while( @array) {
    $tmp = shift( @array);
    print FILE ( $tmp . "\n");  # adding a CR/LF character to maintain file format
}
close FILE;

This may not be the case with a data file with just strings.  If I am working with a datafile that is CR/LF 
delimited, I usually strip the linefeeds off when I buffer the file, then add them back in when I write the data
back to a file.  This method just seems safer and less buggy to me IMHO.

If you have any questions please feel free to contact me.  Hope this helps!

GPG

G.P.Gillis - Software Engineer / Programmer / Technician
gpgillis@xxxx.xxx
http://www.izzy.net/~gpgillis

"We've got computers, we leave 'em on ..."  jimmie's chicken shack

Teach Your Children Well ...


To signoff send a mail to listserver@xxxx.xx.xx with 
  "signoff tcg" in the body of your message.