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.
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.