develooper Front page | perl.perl6.language | Postings from June 2005

BEGIN {...} and IO

Thread Next
Ingo Blechschmidt
June 13, 2005 08:09
BEGIN {...} and IO
Message ID:

  # No problem:
  my $data = BEGIN {
    my $fh = open "some_file" err...;

  # Problem;
  my $fh = BEGIN { open "some_file" err... };
  # Compile-time filehandle leaked into runtime!
  say =$fh;

In Perl 5, this wasn't a problem, as compilation and execution happended
(most of the time) in the same process.

But in Perl 6, compilation and execution can happen in different
processes or even on different computers, so probably the snippet
should raise an error, preferably at compile-time.

My real question: How do I raise an error if objects of my own classes
leak into runtime? I.e.:
  # This should work:
  my $foo = BEGIN { };

  # But this shouldn't:
  my $foo = BEGIN { }.get_some_value;

I can see some possibly answers:

* There should be some bool $?COMPILING:

  class MyClass {
    has Bool $.created_at_compile_time;

    submethod BUILD () {
      $.created_at_compile_time = $?COMPILING;

    method get_some_value () {
      if $.created_at_compile_time and not $?COMPILING {
        die "...";
      } else {

  Pro: Great flexibility (maybe there're two methods, from which only
       one has the restriction that the object may not leak into
  But: The compiler can't check at compile-time if leaking into
       runtime is allowed.

* There should be a special role:

  class MyClass does dont_leak_into_runtime {
    method get_some_value () {...}

  Pro: The compiler can check at compile-time if leakinto into runtime
       is allowed.
  But: You don't have as much flexibility as with $?COMPILING.

* There's a boolean property may_leak_into_runtime every object has,
  with a default of true.
  BEGIN and CHECK then check if the object they're about to return has
  .may_leak_into_runtime set to false -- if that's the case, die:

  class MyClass does may_leak_into_runtime(false) {
    method get_some_value () {...}

  my $foo = BEGIN { }.get_some_value; # really means
  my $foo = BEGIN {
    my $result =;
    $result.may_leak_into_runtime ?? $result :: die "...";

  Pro: Great flexibility, easy to use

FWIW, I like #3 the best.


Linux, the choice of a GNU | Perfection is reached, not when there is no
generation on a dual AMD   | longer anything to add, but when there is
Athlon!                    | no longer anything to take away.           

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About