Forum Moderators: coopster & phranque

Message Too Old, No Replies

How to read a file string

Newbie question

         

Mauricio

9:39 am on Dec 1, 2004 (gmt 0)



Hello.

I'm a webmaster, not a programmer, and I'm trying to write my first script.

By now, my script takes the user's input from a form and writes the data in a file (plain text) with the format

data1 ¦ data2 ¦ data 3 ¦ data 4\n
data1 ¦ data2 ¦ data 3 ¦ data 4\n
data1 ¦ data2 ¦ data 3 ¦ data 4\n
...

I need a little piece of code to do this:
a) the script goes to line1, reads data1
b) do something with data1 (checks if data1 is into a file)
c) if that what it does is right, then go to line2
d) if that what it does is wrong, delete the entire line and do it again (the previous line3 is now line2

It could be something like this:

#!/usr/bin/perl

$htmlfile = 'useful-previous-data.html'

open(DATAFILE,'+<data.txt');

while not EOF { ###?

read DATAFILE,$content 'line1,data1'; ###?

if ($content=~/$htmlfile/g){
goto next line ###?
}
else{
delete line###?
}

}

close(TY);
print <<ENDHTML;

<h1>Done</h1>

ENDHTML
;
exit;

Thanks in advance.

adni18

1:41 pm on Dec 2, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



open(LOGFILE,">>logfile.txt");
@jmain=<LOGFILE>;
$currNum=0;
foreach $carriageLine (@jmain)
{
if(currNum==0)
{

#this is for the first line's actions

$currCache=$carriageLine;

}

else if(currNum > 0)
{

$properties="my condition";

if($properties eq $carriageLine)
{

$currCache=$currCache.$carriageLine;

}

}

$currNum++;
}
close LOGFILE;

moltar

7:28 pm on Dec 2, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This should work, but i haven't tested it

[perl]
#!/usr/bin/perl

$useful_data = 'useful-previous-data.html';

# open file for reading
open DATA, "< $useful_data"
or die "Cannot open $useful_data: $!";

# open temp file
open TEMP, "> $useful_data.tmp"
or die "Cannot create temp file $useful_data.tmp: $!";

while (<DATA>) {
my ($data) = split('\¦', $_, 2);

##
## do something with data
##

# unless what it does is right
unless ( $is_right ) {

# save to temp file
print TEMP $_;
}
}

close(TEMP);
close(DATA);

## once done checking, delete the original file
## and replace it with the temp file
unlink $useful_data;
rename "$useful_data.tmp", $useful_data;[/perl]

P.S. Whatch out for pipe ¦ symbols. They get replaced by broken pipe symbols on this forum.