Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

From single script to code reuse

by Anonymous Monk
on Jul 11, 2017 at 09:23 UTC ( #1194788=perlquestion: print w/replies, xml ) Need Help??
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 (Monsignor) 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 (Monsignor) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1194788]
Front-paged by Corion
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2017-11-19 17:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:













    Results (282 votes). Check out past polls.

    Notices?