In the perl , how to read the contents between two marks. Source data like this
START_HEAD
ddd
END_HEAD
START_DATA
eee|234|ebf
qqq| |ff
END_DATA
--Generate at 2011:23:34
then I only want to get data between “START_DATA” and “END_DATA”. How to do this ?
sub readFile(){
open(FILE, "<datasource.txt") or die "file is not found";
while(<FILE>){
if(/START_DATA/){
record(\*FILE);#start record;
}
}
}
sub record($){
my $fileHandle = $_[0];
while(<fileHandle>){
print $_."\n";
if(/END_DATA/) return ;
}
}
I write this code, it doesn’t work. do you know why ?
Thanks
Thanks
Besides a few typos, your code is not too far off. Had you used
You might have figured it out yourself. Here’s what I found:
Normal sub declaration is
sub my_function (prototype) {, but you can leave out the prototype and just usesub my_function {.while (<fileHandle>) {is missing the$sign to denote that it isa variable (scalar) and not a global. Should be
$fileHandle.print $_."\n";will add an extra newline. Justprint;will dowhat you expect.
if(/END_DATA/) return;is a syntax error. Brackets are not optionalin perl in this case. Unless you reverse the statement.
Use either:
or
Below is the cleaned up version. I commented out your
open()while testing, so this would be a functional code example.