jonah_w
jonah_w

Reputation: 1032

BEGIN and END in Perl

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.

Upvotes: 1

Views: 254

Answers (1)

choroba
choroba

Reputation: 241768

When the BEGIN block runs (i.e. when compiling the source code), the file handle is not yet opened. You can verify it with

perl -nE 'BEGIN { say $ARGV }'

Upvotes: 5

Related Questions