Not so with perl in which the BEGIN block is intended for code that must be executed before anything else, perl would otherwise select certain code for processing (such as use or require of an external file), earlier than is indicated by its position in the program. The BEGIN block overrides that feature for its contents.
But the first line of code OUTSIDE any BEGIN block will still get executed before the file is opened, e.g.:
#!/usr/bin/perl use strict; use warnings; my $file = '/path/file.dat'; my $exists = ( -e $file ); my $normal = ( -f $file ); $exists and (not $normal) and die "$file is unsuitable for this progra +m"; my $iocmd = $normal ? "<$file" : ">$file"; # until now we could check the existence of the file # and how to open it and we did not need BEGIN open my $fh, $iocmd or die "$!, for $file"; my @content = $normal ? <$fh> # only now is the file read in if exists :( "I am\n", "the default\n", "contents\n" ); $normal or print $fh @content; # or printed to otherwise close $fh or die "$!, for $file"; # now both the file and @content contain either tbe # program default or previously stored content depending on # whether the file existed.
-M
Free your mind
In reply to Re: BEGIN and END blocks, use strict and scoping
by Moron
in thread BEGIN and END blocks, use strict and scoping
by jkeenan1
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |