I'm trying to obtain some data of specific pattern from a text file in BEGIN
block and print them in the END
block, as follows:
perl -0777wnE'
BEGIN{
while(/<mark>(.*?)<\/mark>/g){
$hw=$1;
$seen{$hw}++;
}
}
END{
for $key (keys %seen){
say "$key";
}
}
' "demo.txt" > "demo2.txt"
But it doesn't print anything into the demo2.txt file, and it gives the following warning:
Use of uninitialized value $_ in pattern match (m//) at -e line 3.
But if I put the while
block outside of BEGIN
block , like this:
perl -0777wnE'
while(/<mark>(.*?)<\/mark>/g){
$hw=$1;
$seen{$hw}++;
}
END{
for $key (keys %seen){
say "$key";
}
}
' "demo.txt" > "demo2.txt"
Then it gets the expected results.
When the BEGIN block runs (ie when compiling the source code), the file handle is not yet opened. You can verify it with
perl -nE 'BEGIN { say $ARGV }'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.