Home > Archive > PERL Beginners > November 2006 > Blocks location
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
|
|
| Jm lists 2006-11-21, 6:57 pm |
| Hello members,
How about the BEGIN and END blocks in the perl scripts?Is the BEGIN block
needed to be put just at the begin of script-file,and END block needed to be
put just at the end of file?Thanks.
| |
|
| --- Jm lists <practicalperl@gmail.com> wrote:
> Hello members,
>
> How about the BEGIN and END blocks in the perl scripts?Is the BEGIN
> block
> needed to be put just at the begin of script-file,and END block
> needed to be put just at the end of file?Thanks.
No, they can be put anywhere in the program. BEGIN blocks will be
executed in the order encountered, during the compilation phase:
#!/use/bin/perl -l
print 1;
BEGIN { print 'one' }
print 2;
BEGIN { print 'two' }
print 3;
That should print:
one
two
1
2
3
The 'one' and 'two' print before the digits because BEGIN blocks are
executed as soon as they are encountered in the compilation phase.
END blocks are executed at the end of the program, in reverse order
they are encountered:
#!/usr/bin/perl -l
END { print 3 }
END { print 4 }
BEGIN { print 1 }
BEGIN { print 2 }
That prints:
1
2
4
3
Hope that helps. You can insert a few print statements in there to get
a better idea of how it compiles and executes.
Cheers,
Ovid
--
Buy the book -- http://www.oreilly.com/catalog/perlhks/
Perl and CGI -- http://users.easystreet.com/ovid/cgi_course/
| |
| Paul Lalli 2006-11-21, 6:57 pm |
| Ovid wrote:
> #!/usr/bin/perl -l
> END { print 3 }
> END { print 4 }
> BEGIN { print 1 }
> BEGIN { print 2 }
>
> That prints:
>
> 1
> 2
> 4
> 3
>
> Hope that helps. You can insert a few print statements in there to get
> a better idea of how it compiles and executes.
See also the example that uses not only BEGIN and END blocks but also
CHECK and INIT blocks, found in:
perldoc perlmod
Paul Lalli
|
|
|
|
|