views:

217

answers:

3

I am still new to Perl. Since BEGIN blocks are run during compilation can't a virus spread or data loss occur from simply compiling? Does Perl do anything to stop it? If so does it mean the code in BEGIN blocks may act differently outside of it?

+13  A: 

Yes to all these questions. The Eclipse IDE was vulnerable to this. It discussed in more detail here.

As with all software, you should avoid downloading and running anything from a source you do not trust. CPAN is generally trustworthy; although I am not aware of anyone intentionally releasing rogue code to CPAN, it's possible it has happened.

You can avoid running code during compile checks with the $^C flag, e.g.:

BEGIN { load_data_from_db() unless $^C; }
Ether
Excellent point about `$^C`. Here's a link to the perlvar entry for it: http://perldoc.perl.org/perlvar.html#$^C
daotoad
@daotoad your link was broken, so I edited the response to contain a working one.
Ether
+1  A: 

Note that sometimes this is a feature. BEGIN blocks inside mod_perl modules are executed only once, when they are first loaded. So you have a simple syntax to do page-level initialization in the same script, and place it "near" the code that it assists.

Occasionally it's similarly useful for writing complicated initialization code that you don't want to put at the top of a script.

But mostly it's just there for thematic compatibility with awk.

Andy Ross
It's there for a lot more than looking like awk. BEGIN blocks are very useful for sequencing things.
brian d foy
Isn't that exactly what I said? There was quite a bit of text before the sentence you decided to pick on..
Andy Ross
@Andy - you said "mostly". In my many years of Perl software development, I have used (and seen it used) BEGIN blocks for a number of reasons on miriad of occasions, and not ONCE have I seen it used "thematic compatibility with awk".
DVK
+2  A: 

chromatic explains how a Perl program works.

deepakg