in reply to Variables out of scope using END and Error.pm

It's a problem with closures in current versions of perl. Named subs (such as END) don't close on behalf of inner anonymous subs (such as the try block effectively is), so the variable goes out of scope before END is called. The presence of the variable directly in the END sub causes the variable to be captured and thus live long enough for END to be called. It's already fixed (by me :-) in the development branch of perl:
$ cat /tmp/p #!/usr/bin/perl -w my $x = 1; END { sub { print "x=$x\n" }->(); } $ perl586 /tmp/p Use of uninitialized value in concatenation (.) or string at /tmp/p li +ne 5. x= $ perl590 /tmp/p x=1 $

Dave.

Replies are listed 'Best First'.
Re^2: Variables out of scope using END and Error.pm
by Animator (Hermit) on Feb 17, 2005 at 20:01 UTC

    I'm not sure if that explenation is 100% correct...

    If for example you change 'END' to sub abc (or anything, which is a named sub aswell) else and call it, then it does print 1.

      I'm not sure if that explenation is 100% correct...
      On the other hand, I am sure :-)

      The only difference between END and a normal sub in this case is that the END is called after the variable has normally gone out of scope. The following demonstrates the buggy behaviour for ordinary subs (on perl < 5.9.0) by artifically reducing the scope of the variable

      { my $x = 1; sub foo { # commenting this out causes the print to see an undef value $x; sub { print "x=$x\n" }->(); } } foo();

      Dave.