in reply to BEGIN and END blocks, use strict and scoping

Note: In your "Case 3", you had an error in understanding. "use" statements are implicitly wrapped in a BEGIN block.

As for your goal, why not do something like:

#! perl use strict; my $filename = 'C:/shb'; my $action; if ( -f $filename ) { $action = 'rename'; } else { $action = 'create'; } END { if ($action eq 'rename') { } else { } }

My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

Replies are listed 'Best First'.
Re^2: BEGIN and END blocks, use strict and scoping
by jkeenan1 (Deacon) on Sep 24, 2005 at 13:24 UTC
    If I understand you correctly, the END block can make use of lexical variables defined in the file before the END block itself. This would obviate the need for using a BEGIN block to test for the presence/absence on disk of a given file. It would also mean that I could place use strict; in its customary position.

    The following little script should illustrate the point in various ways depending on whether the file present is indeed present and depending on whether the croak call is live or commented-out.

    Update: While the solution above guarantees that the testing process is (more) non-destructive, it does have one drawback, AFACIT. When the croak occurs earlier in the file, (1) the total number of tests run is reduced by the quantity lying between the croak and the END block and (2) the numbers associated with the tests inside the END block are no longer at the end of the range predicted by the plan.

    Revised example:

    ... produces (assuming that present was indeed present at the outset):

    1..7 ok 1 - original file no longer present ok 2 - hidden file present Trick is false at end.pl line 28 ok 3 - hidden file no longer present ok 4 - original file once again present # Looks like you planned 7 tests but only ran 4. # Looks like your test died just after 4.
    Tests 3 and 4 above are not the third and fourth as you would intuitively predict from eyeballing the file. You become more dependent on the croak message in locating the error within the file.

    Thanks!

    Jim Keenan

      Now, you move from having an issue with understanding how use and BEGIN work to an issue with how Test::More works. Modify your code as such:
      unless ( $trick ) { SKIP: { skip 3, "About to croak!\n"; } croak; } else { # Do your three other tests here. }
      You just have to let Test::More know what's going on with regards to your test plan. It's called a plan for a reason.

      My criteria for good software:
      1. Does it work?
      2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?