Dan Brook

NAME

Sub::Lexical - implements lexically scoped subroutines

SYNOPSIS

  use Sub::Lexical;

  sub foo {
      my @vals = @_;

      my sub bar {
          my $arg = shift;
          print "\$arg is $arg\n";
          print "\$vals are @vals\n";
      }

      bar("just a string");

      my sub quux (@) {
          print "quux got args [@_]\n";
      }

      takesub(\&quux, qw(ichi ni san shi));
  }

  sub takesub { print "executing given sub\n\t"; shift->(@_[1..$#_]) }

  foo(qw(a bunch of args));

DESCRIPTION

Using this module will give your code the illusion of having lexically scoped subroutines. This is because where ever a sub is lexically declared it will really just turn into a my()ed scalar pointing to a coderef.

However the lexically scoped subs seem to work as one might expect them to. They can see other lexically scoped variables and subs, and will fall out of scope like they should. You can pass them around like coderefs, give them attributes and prototypes too if you're feeling brave. Another advantage is you can use them as truly private methods in packages, thereby realising the dream of true encapsulation so many have dreamed of.

Your code will be automatically parsed on include (this is a filter module after all) so the methods listed below are provided so you can filter your own code manually.

METHODS

new

Typical constructor will return a Sub::Lexical object. Must be called as a class method at the moment

subs_found

Returns an ArOH of the form

  [
    {
    'code' => '{ ... }',
    'extra' => '() : attrib',
    'name' => 'foo'
    }
  ]
filter_code

It takes one argument which is the code to be filtered and returns a copy of that code filtered e.g

  my $f = Sub::Lexical->new();
  $filtered = $f->filter_code($code);

CAVEATS

  • If you have a sub called foo it will clash with any variable called LEXSUB_foo within the same scope, as all subs have 'LEXSUB_' appended to them so as to avoid namespace clashes with other variables (any suggestions for a cleaner workaround are very much welcome).

SEE ALSO

perlsub, Regex::Common, Filter::Simple

THANKS

Damian Conway and PerlMonks for giving me the skills and resources to write this

AUTHOR

by Dan Brook <broquaint@hotmail.com>

COPYRIGHT

Copyright (c) 2002, Dan Brook. All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.