Gossamer Forum
Home : General : Perl Programming :

Re: [Paul] Setting specific line in file as variable

Quote Reply
Re: [Paul] Setting specific line in file as variable In reply to
Paul asked "Did you open/close the file twice to solve it?"

I'm not sure if you were asking Peter, or asking me (the one who pasted the code for Peter to try), but I didn't open/close it twice (Peter may have, though.

I just found a potential "bug" in my code, though, so here's a redo (whole thing, so you'll see what I'm thinking):


# OPTION 1 (for when you're going to be checking the same file over and over again
open (FILE, "data.txt") || die "can't read from data.txt";
@lines=<FILE>;
close (FILE);
foreach $line(@lines) {
$line=$1 if ($line=~/^(.*)$/); # I like to untaint stuff .... 'specially when working with paths, but do it pretty much all the time just for good measure :-)
if ($line=~/^$goto/) {
# do your stuff, the line is already assigned to the variable '$line'
last;
}
}


# OPTION 2 (if you'll only be checking once for a match)
$line=''; # (predeclare the variable)
open (FILE, "data.txt") || die "can't read from data.txt";
while (<FILE>) {
if ($_=~/^$goto(.*)$/) { # untaint and match at the same time, leaving the variable '$line' null if no match found (ignores any lines that don't start with '$goto').
$line=$_;
# Do your stuff
last;
}
}
close (FILE);


Both ways, it only opens/closes data.txt once.
Subject Author Views Date
Thread Setting specific line in file as variable petermcdonald 6410 Sep 1, 2002, 4:21 PM
Thread Re: [petermcdonald] Setting specific line in file as variable
durp 6281 Sep 1, 2002, 10:08 PM
Thread Re: [durp] Setting specific line in file as variable
petermcdonald 6289 Sep 1, 2002, 10:50 PM
Thread Re: [petermcdonald] Setting specific line in file as variable
petermcdonald 6281 Sep 1, 2002, 11:06 PM
Thread Re: [petermcdonald] Setting specific line in file as variable
Paul 6265 Sep 2, 2002, 2:10 AM
Post Re: [Paul] Setting specific line in file as variable
durp 6260 Sep 2, 2002, 10:31 AM
Thread Re: [Paul] Setting specific line in file as variable
petermcdonald 6250 Sep 2, 2002, 10:34 AM
Thread Re: [petermcdonald] Setting specific line in file as variable
petermcdonald 6273 Sep 2, 2002, 10:37 AM
Post Re: [petermcdonald] Setting specific line in file as variable
Paul 6265 Sep 2, 2002, 10:50 AM
Thread Re: [petermcdonald] Setting specific line in file as variable
Paul 6226 Sep 2, 2002, 10:56 AM
Thread Re: [Paul] Setting specific line in file as variable
petermcdonald 6244 Sep 2, 2002, 11:07 AM
Thread Re: [petermcdonald] Setting specific line in file as variable
Paul 6243 Sep 2, 2002, 11:34 AM
Thread Re: [Paul] Setting specific line in file as variable
petermcdonald 6256 Sep 2, 2002, 11:55 AM
Thread Re: [petermcdonald] Setting specific line in file as variable
Paul 6249 Sep 5, 2002, 4:21 AM
Post Re: [Paul] Setting specific line in file as variable
petermcdonald 6207 Sep 7, 2002, 6:07 PM