Peter Rabbitson
Jul 7 2005, 05:16 AM
Hello everyone,
Most modules I run across have a BEGIN block containing some variable
declarations, module loaders etc. Although I understand what BEGIN is
(code being evaluated immediately after it is parsed), I miss the point
of the excercise. For example:
package csv_generator;
use Text::CSV_XS;
our $ERROR;
sub new {
my $class = shift;
return (bless {}, $class);
}
sub add_line {
my $self = shift;
push @{$self->{pending}}, [@_];
return 1;
}
sub wrap_csv {
my $self = shift;
my $csv = Text::CSV_XS->new;
my @result;
foreach my $line @{$self->{pending}} {
$csv->combine (@{$line});
push @result, $csv->string();
}
return (join ("n", @result));
}
Where would BEGIN come to play?
P.S. I know the above code is messy, without any error checking, and I
might even have a typo somewhere. It is just for illustration purposes.
Peter Rabbitson
Jul 7 2005, 05:34 AM
On Thu, Jul 07, 2005 at 02:22:34AM -0400, Casey West wrote:
QUOTE |
This is a confusing question, but I think the answer is that a BEGIN block would come into play before any of these things are executed.
-- Casey West
|
Sorry :) Question is: why would I want to use a BEGIN block in the above
script skeleton. What advantages would BEGIN give me that I can not have
otherwise, and why most modules bear one (some more than one).
Xavier Noria
Jul 7 2005, 12:05 PM
On Jul 7, 2005, at 8:16, Peter Rabbitson wrote:
QUOTE |
Hello everyone, Most modules I run across have a BEGIN block containing some variable declarations, module loaders etc. Although I understand what BEGIN is (code being evaluated immediately after it is parsed), I miss the point of the excercise.
|
It is very simple: BEGIN is appropriate when you need something to be
executed at compilation time. That's it. If your code does not need
anything to be executed there, then you don't need a BEGIN block. You
seem to assume that the lack of BEGIN blocks in your programs is
suspicious, as if you were missing something. Well, probably you
don't, BEGIN blocks are not that common in everyday programming, I
need them just occasionally.
-- fxn
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please
click here.