John Verber
John Verber

Reputation: 755

Read Increment Then Write to a text file in perl

I have this little perl script which opens a txt file, reads the number in it, then overwrites the file with the number incremented by 1. I can open and read from the file, I can write to the file but I"m having issues overwriting. In addition, I'm wondering if there is a way to do this without opening the file twice. Here's my code:

#!/usr/bin/perl

open (FILE, "<", "data.txt") or die "$! error trying to a\
ppend";

 undef $/;

$number = <FILE>;
$number = int($number);
$myNumber = $number++;
print $myNumber+'\n';
close(FILE);

open(FILE, ">data.txt") or die "$! error";
print FILE $myNumber;
close(FILE);

Upvotes: 1

Views: 3493

Answers (3)

Kenosis
Kenosis

Reputation: 6204

It's good that you used the three-argument form of open the first time. You also needed to do that in your second open. Also, you should use lexical variables, i.e., those which begin with my, in your script--even for your file handles.

You can just increment the variable that holds the number, instead of passing it to a new variable. Also, it's a good idea to use chomp. This things being said, consider the following option:

#!/usr/bin/env perl

use strict;
use warnings;

undef $/;

open my $fhIN, "<", "data.txt" or die "Error trying to open for reading: $!";
chomp( my $number = <$fhIN> );
close $fhIN;

$number++;

open my $fhOUT, ">", "data.txt" or die "Error trying to open for writing: $!";
print $fhOUT $number;
close $fhOUT;

Another option is to use the Module File::Slurp, letting it handle all the I/O operations:

#!/usr/bin/env perl
use strict;
use warnings;
use File::Slurp qw/edit_file/;

edit_file { chomp; $_++ } 'data.txt';

Upvotes: 3

Jim Black
Jim Black

Reputation: 1482

Try this:

#!/usr/bin/perl
use strict;
use warnings;
my $file = "data.txt";
my $number = 0;
my $fh;
if( -e $file ) {
    open $fh, "+<", $file or die "Opening '$file' failed, because $!\n";
    $number = <$fh>;
    seek( $fh, 0, 0 );
} else {                  # if no data.txt exists - yet
    open $fh, ">", $file or die "Creating '$file' failed, because $!\n";
}
$number++;
print "$number\n";
print $fh $number;
close( $fh );

If you're using a bash shell, and you save the code to test.pl, you can test it with:

for i in {1..10}; do ./test.pl; done

Then 'cat data.txt', should show a 10.

Upvotes: 0

Rush
Rush

Reputation: 496

Change the line

$myNumber = $number++;
to 
$myNumber = $number+1;

That should solve the problem.

Below is how you could do by opening the file just once:

 open(FILE, "+<data.txt") or die "$! error";
 undef $/; 

 $number = <FILE>;
 $number = int($number);
 $myNumber = $number+1;
 seek(FILE, 0, 0); 
 truncate(FILE, tell FILE);
 print $myNumber+"\n";

 print FILE $myNumber;
 close(FILE);

Upvotes: 3

Related Questions