On Sun, 2004-01-25 at 14:33, [EMAIL PROTECTED] wrote:
> Hi all:
> 
> I'm trying to put a variable value into a text file.  I've tried a few 
> things with no success. 
> 
> Anyone know how to do this ?  Is it doable ?  I'm pretty sure I read how 
> to do this somewhere, so I'm about to hit the Perl books  to see if I can 
> find it. 
> Any help will be appreciated.
> 
> Here's what I last tried.  It doesn't work and I'm embarrassed to even 
> show it.  But, I did want to show that at least I'm trying to make it 
> work:
> 
> use strict;
> use warnings;
> 
> open (INFILE, "c:\\testmessage.txt") or die "The source file failed to 
> open - $!";
> my @testarray = <INFILE>;
> my $name = "stuart";
> print @testarray;
> 
> Here's what it prints:  My name is $name.
> 
> Here's the testmessage.txt file:  My name is $name.
> 
> After running my script, I'd like the testmessage.txt to read:  My name is 
> stuart.
> 
> Thanks again for any help.

Hi Stuart,

>From the Perl Cookbook Chapter 7, Recipe 10 "How to modify a file in
place without a temporary file".

open(FH, "+< FILE")                 or die "Opening: $!";
@ARRAY = <FH>;
# change ARRAY here
seek(FH,0,0)                        or die "Seeking: $!";
print FH @ARRAY                     or die "Printing: $!";
truncate(FH,tell(FH))               or die "Truncating: $!";
close(FH)                           or die "Closing: $!";

The idea is that you read the file into an array (each element
in the array is a line), modify the lines in the array you'd like to,
then "Seek" the file position back to the beginning and write the array
to the file, therefore resulting in a "modified" file.

HTH,
Kevin
-- 
Kevin Old <[EMAIL PROTECTED]>


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to