[ABE.pm] Sub::Exporter!

Ricardo SIGNES rjbs-perl-abe at lists.manxome.org
Sat May 6 20:40:05 PDT 2006


So, the one Perl thing that we did talk about a good bit was one of my current
projects, Sub::Exporter.  It's a replacement for Exporter.pm, the default (but
boring and antiquated symbol exporter.  The exporter is what makes this work:

  use LWP::Simple qw(get);

  my $contents = get 'http://www.cnn.com';

Sub::Exporter would let you support something like this:

  use LWP::Simple::SE;
    get => { proxy => 'http://10.2.0.1:8080' },
    get => { -as => 'get_direct };

  die "proxy and direct are different!"
    unless get($ARGV[0]) eq get_direct($ARGV[0]);

The setup to use Sub::Exporter, above, might look something like this:

  package LWP::Simple::SE;
  use Sub::Exporter -setup => {
    exports => { get => \&get_builder },
  };

  sub get_builder {
    my ($class, $name, $arg) = @_;
    my $custom_get = sub {
      my ($url) = @_;
      get($url, $arg);
    }

    return $custom_get;
  }

  sub get { ... }

Then, our call to the get built with a proxy would really be a call to:

  LWP:Simple::SE::get($url, { proxy => ... });

This is largely through the magic of closures:  usually-anonymous subroutines
that include hidden variables.  Closure factories let you build little tools
that behave just like you want and that can go away when you're done.

If you think this sounds cool, you should consider looking into one of three
things:

* Sub::Exporter

  http://search.cpan.org/dist/Sub-Exporter
  This is the distribution of Sub::Exporter.  Its docs may be demonstrative;
  it's free and right there.

* Intermediate Perl

  This is basically "Learning Perl, vol 2" from O'Reilly.  It just came out,
  and I received a copy in the mail.  It covers references, objects, and
  modules.  If you understand the contents of Learning Perl, you should give
  Intermediate Perl a go.  It's where Perl starts to shine for a programmer, in
  my opinion.  I was a technical reviewer on this book, and I can say that it's
  Darn Good.  Chapter 7 is all about closures!

* Higher-Order Perl

  If you totally understand closures and how to build and use them, pick up
  this fantastic book and find out that you have a lot more to learn.  It's a
  book about using functional programming techniques (like closures) to make
  your Perl 100% more awesome.

-- 
rjbs
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://mail.pm.org/pipermail/abe-pm/attachments/20060506/5ef26c3d/attachment.bin 


More information about the ABE-pm mailing list