CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Need a Custom or Prewritten Perl Program?: I need a program that...:
Script to append a file only once and return error on subsequent run

 



yashukla
Novice

Jun 17, 2010, 10:41 AM

Post #1 of 2 (2124 views)
Script to append a file only once and return error on subsequent run Can't Post

I want to write a perl script that appends "My_File.txt" with a "string" when the script is run for the very first time.

Subsequently if I run this script again, I shud get a message that "string" is already appended in "My_File.txt".

I've written a code, but it is not giving the desired result. Pls let me know the issue with this script and suggest a relevent solution for the same..

Code
#!C:/Perl/bin/perl.exe -w  

$My_File="D:/My_File.txt";

$Target= "ADD_STRING_HERE";

open($My_File_FP,"<$My_File") || die("This file will not open!");

while(<$My_File_FP>)
{
if (/$Target/)
{
print " found $Target on line $. \n";
close($My_File_FP);
}
else
{
open($My_File_FP,">>$My_File") || die("This file will not open!");
print $My_File_FP "\n ADD_STRING_HERE \n";

}
}
close($My_File_FP);


Pls let e kno the issue... I'm a newbie in Perl and want to lear more thru this forum..

Thanks in advance!
Shocked


dva300
New User

Jun 20, 2010, 7:26 AM

Post #2 of 2 (2081 views)
Re: [yashukla] Script to append a file only once and return error on subsequent run [In reply to] Can't Post

hi,
you can try this one. i hope this script can help you.


Code
use strict; 
my $file_name = "test.txt";
my $string = "TEST_STRING";
my $flag = 1;
#
# file should be exist. you can use any other programs to do this. for example touch under Unix system
#
if (!(-e $file_name))
{
open(FF,">$file_name") or die "Cann't crate file $file_name : $!\n";
close(FF);
}
#
# open file in read/write mode
#
open(FF,"+<$file_name") or die "error $!\n";
while(<FF>)
{
if (/^$string$/)
{
print "String [$string] is exist in the file [$file_name]\n";
$flag = 0;
last;
}
}
print FF "$string\n" if ($flag);
close(FF);


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives