What is the role of the BEGIN block in Perl?

前端 未结 3 1539
青春惊慌失措
青春惊慌失措 2021-01-31 15:49

I know that the BEGIN block is compiled and executed before the main body of a Perl program. If you\'re not sure of that just try running the command perl -cw over this:

3条回答
  •  不知归路
    2021-01-31 16:26

    While BEGIN and END blocks can be used as you describe, the typical usage is to make changes that affect the subsequent compilation.

    For example, the use Module qw/a b c/; statement actually means:

    BEGIN {
       require Module;
       Module->import(qw/a b c/);
    }
    

    similarly, the subroutine declaration sub name {...} is actually:

    BEGIN {
       *name = sub {...};
    }
    

    Since these blocks are run at compile time, all lines that are compiled after a block has run will use the new definitions that the BEGIN blocks made. This is how you can call subroutines without parenthesis, or how various modules "change the way the world works".

    END blocks can be used to clean up changes that the BEGIN blocks have made but it is more common to use objects with a DESTROY method.

    If the state that you are trying to clean up is a DBI connection, doing that in an END block is fine. I would not create the connection in a BEGIN block though for several reasons. Usually there is no need for the connection to be available at compile time. Performing actions like connecting to a database at compile time will drastically slow down any editor you use that has syntax checking (because that runs perl -c).

提交回复
热议问题