How do I write to the same line in a file after reading from the that line.
#!/usr/contrib/bin/perl
$i = "c.txt";
$flag = 0;
if (-e $i )
{
open(RW,"+<", $i);
}
else
{
open(RW,"+>", $i);
print RW "0";
$flag = 1;
}
if($flag == 0)
{
while(<RW>)
{
$tmp = $_;
}
$tmp=$tmp+1;
print RW $tmp;
}
close RW;
I want this program to create a file called c.txt if it doesnot exist and on the first run of the perl script it should write a '0' to first line in the file. the next time I run the script, it should read the first line(i.e. a 0), increment it by 1 and then re-write to the same line. i.e. the first line on the file should be written with '1'.
Currently when i run the script for the first time, it correctly write a '0' on the first line but when I rerun the script it appends the incremented value i.e. a '1' (writes a '01') on the first line. I expect it to write a '1' on first line.
Any help is appreciated.
Thanks
#!/usr/contrib/bin/perl
$i = "c.txt";
$flag = 0;
if (-e $i )
{
open(RW,"+<", $i);
}
else
{
open(RW,"+>", $i);
print RW "0";
$flag = 1;
}
if($flag == 0)
{
while(<RW>)
{
$tmp = $_;
}
$tmp=$tmp+1;
print RW $tmp;
}
close RW;
I want this program to create a file called c.txt if it doesnot exist and on the first run of the perl script it should write a '0' to first line in the file. the next time I run the script, it should read the first line(i.e. a 0), increment it by 1 and then re-write to the same line. i.e. the first line on the file should be written with '1'.
Currently when i run the script for the first time, it correctly write a '0' on the first line but when I rerun the script it appends the incremented value i.e. a '1' (writes a '01') on the first line. I expect it to write a '1' on first line.
Any help is appreciated.
Thanks