On Wed, Feb 07, 2001 at 05:15:41PM -0600, David L. Nicol wrote:
> Nicholas Clark wrote:
> > 
> > On Wed, Feb 07, 2001 at 04:30:24PM -0600, David L. Nicol wrote:
> > 
> > >       sub has_post_blocks{
> > >               my $i = 3;
> > >               post { print "i ended up as $i"};
> > >               my $arg1 = shift; $arg1 > 4 or die "arg1 ($arg1) too small";
> > >               my $j = 2;
> > >               post { print "j ended up as $j"};
> > >               ...
> > >       };
> > >
> > > might only print the message about i when arg1 is too small.  This would
> > > allow informational messages to be declared at the beginning, for instance.
> > >
> > > It would be implemented by pushing the post block onto the list of things
> > > to do at scope exit, at run time.
> > 
> > I quite like this idea.  (I certainly like the ability to say "clean up this
> > thing at the end of scope whatever exceptions may happen)
> > 
> > But part of me feels it should be a POST block.
> > Because it's behaving much like CHECK or END
> > 
> > Nicholas Clark
> 
> 
> Do you agree that they shouldn't get tacked on until execution passes their
> definition, unlike END blocks which get appended when they are parsed?

It makes them far more useful as tidy up things if they are tacked on at
runtime, not compile time.
The sort of job I'm thinking of is "release this lock" or "close this file"
which you don't want to both with if you never got that far into the sub

You can do it at the moment by making a object where DESTROY does your
cleaning up, but it's a lot less clear having your cleanup code somewhere
else [hmm. I never considered passing an object an anonymous sub for it
to run at DESTROY time...] than having the cleanup code nearby

Of course if these hypothetical POST blocks did get tacked on at compile
time you could achieve the run time effect by having a flag that you don't
set until needed

{
  my $flag;
  open FOO, "<bar" ? $flag=1 : die "aargh $!";
  POST {close FOO if $flag};
  ...
}

but that removes the benefit of having them inline near the thing they are
tidying up.

[on the other hand, I'll argue the other side that

{
  my $flag
  open FOO, "<bar" ? $flag=1 : die "aargh $!";
  ...
}
post {
  close FOO if $flag;
}

is clearer because the tidy up doesn't visually get in the way of the flow
of what you're doing, and you can see what $flag is meant to be

(or whatever the syntax I'm going to get wrong because I can't remember all
of this thread or its precursors and I confess I've still not read the
relevant RFCs recently. Sorry)

and a POST block that is run time when other things are compile time isn't
totally consistent.
]



> perl -nle 'print 0; $_ and eval {BEGIN{print 1};END{print 2}}; print 3'
> 
> only prints one 1 and one 3.

did you mean 2?



Nicholas Clark

Reply via email to