http://www.perlmonks.org?node_id=1194788

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

I have a for loop which right now prints results to the screen liek:

for my $result ( $mech->links() ){ print "title: $result->name\n"; print "text: $result->text\n"; }


Now I want to make this a generic thing, a module accessible to other scripts I write. What data structure is best to use, how can I return this to the calling scripts? What in perldoc do I need to read and understand?

Replies are listed 'Best First'.
Re: From single script to code reuse
by haukex (Archbishop) on Jul 11, 2017 at 09:40 UTC

    What API you provide depends a bit on what kind of data you want to return. It looks like you're scraping links, so for example, you could have one part of your code return those links as a Perl data structure, which you can then feed into other parts of the code. In that respect, perlreftut and perldsc are probably good reads. Here's just one quick untested idea, and remember, TIMTOWTDI.

    sub getlinks { my ($mech,...) = @_; ... code to get the webpage here ... my @links; for my $result ( $mech->links() ) { push @links, { title=>$result->name, text=>$result->text }; } return \@links; }

    In general, for modularizing code, depending on what level you're starting at, there's perlsub, perlmod, and perlootut, or the book Modern Perl also has chapters on modules and OO.

    As for the general question in the title, see e.g. Moving from scripting to programming.

Re: From single script to code reuse
by Discipulus (Canon) on Jul 11, 2017 at 11:26 UTC
    See the basic docs linked by haukex and the CORE module Exporter and also Perl Modules and my bookmarks about modules

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.