Subject: | ProhibitNestedSubs and scheduled blocks |
Date: | Sat, 31 Oct 2009 09:01:33 +1100 |
To: | bug-Perl-Critic [...] rt.cpan.org |
From: | Kevin Ryde <user42 [...] zip.com.au> |
I noticed ProhibitNestedSubs reports a violation on something like
BEGIN {
sub foo {
}
}
It'd be good if it explained what's bad about that, maybe along the
lines below.
I was going to say the policy should allow such nesting, but if I'm
right about the nature of scheduled blocks then the prohibition is
reasonable, it just needs an explanation, since code like that doesn't
look like a nested sub { sub { ... } } as described in the docs.
Index: ProhibitNestedSubs.pm
===================================================================
--- ProhibitNestedSubs.pm (revision 3692)
+++ ProhibitNestedSubs.pm (working copy)
@@ -71,7 +71,7 @@
sub do_something {
...
- sub do_subprocess {
+ sub do_subprocess { # not ok
...
}
...
@@ -80,8 +80,31 @@
C<do_subprocess()> is global, despite where it is declared. Either
write your subs without nesting or use anonymous code references.
+=head2 Scheduled Blocks
+Remember scheduled blocks (see L<perlmod/BEGIN, UNITCHECK, CHECK, INIT and
+END>) are effectively anonymous subs to be executed as the corresponding time,
+and so nested subs within them are global too.
+ END {
+ sub something { # not ok
+ ...
+ }
+ }
+
+If you want to scope down some private variables then a plain surrounding
+block is likely to be clearer than a nested sub.
+
+ {
+ my $x;
+ sub foo { # ok, still global, but not nested
+ print $x,"\n";
+ }
+ END {
+ $x = ...;
+ }
+ }
+
=head1 CONFIGURATION
This Policy is not configurable except for the standard options.