windowbreaker has asked for the wisdom of the Perl Monks concerning the following question:

I am reading thru the code in the Web::Scraper module, and don't understand how the imported subroutine named scraper is returning a Web::Scraper object.

In Web/Scraper.pm you have this

sub import { ... *{"$pkg\::scraper"} = _build_scraper($class); } sub _build_scraper { my $class = shift; return sub(&) { my($coderef) = @_; bless { code => $coderef }, $class; }; }

I get that scraper executes _build_scraper, which is a prototyped sub that takes a coderef as it's only argument. But it looks to me that calling scraper { } from the client code will return not a Web::Scraper object, but a CODEREF that, when executed, will return a Web::Scraper object using the sub{} block given to scraper{}.

If anyone can shed light on this to help me better understand what's happening that would be great.

Replies are listed 'Best First'.
Re: How is this sub returning an object instead of a CODEREF
by Corion (Patriarch) on Jul 13, 2012 at 17:26 UTC

    The difference is quite subtle:

    *{"$pkg\::scraper"} = _build_scraper($class);

    ... and what you thought you saw was (or at least, I thought I saw that, for a moment):

    *{"$pkg\::scraper"} = \&_build_scraper($class);

    This installs the result of  _build_scraper($class); as the sub scraper in your code.

    And the result of _build_scraper($class) is what returns objects.

      Good catch, I didn't see that. Thanks.