What is the role of the BEGIN block in Perl?

前端 未结 3 1528
青春惊慌失措
青春惊慌失措 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:24

    While the other answers are true, I find it also worth to mention the use of BEGIN and END blocks when using the -n or -p switches to Perl.

    From http://perldoc.perl.org/perlmod.html

    When you use the -n and -p switches to Perl, BEGIN and END work just as they do in awk, as a degenerate case.

    For those unfamiliar with the -n switch, it tells Perl to wrap the program with:

    while (<>) {
        ...  # your program goes here
    }
    

    http://perldoc.perl.org/perlrun.html#Command-Switches if you're interested about more specific information about Perl switches.

    As an example to demonstrate the use of BEGIN with the -n switch, this Perl one-liner enumerates the lines of the ls command:

    ls | perl -ne 'BEGIN{$i = 1} print "$i: $_"; $i += 1;'
    

    In this case, the BEGIN-block is used to initiate the variable $i by setting it to 1 before processing the lines of ls. This example will output something like:

    1: foo.txt
    2: bar.txt
    3: program.pl
    4: config.xml
    

提交回复
热议问题