Although in perl, you don't need the BEGIN block to achieve the stated goal. It would be different if you were using awk instead of perl, because in awk, the only place to put any code that must execute before the first line if input is read in is the BEGIN block.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.