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

Hi all,

I am pretty new to perl and this might be a stupid question but i was wondering how can i separate my code in pieces and run them all from one file, like the way you can do in PHP using include(filename.php). Is this possible or do i have to write a module for each part?

Thanks

Replies are listed 'Best First'.
Re: calling a perl file from a perl script
by friedo (Prior) on Apr 06, 2007 at 19:39 UTC
    You can run code in external files using require or do, but it's almost always a better idea to use a module for this sort of thing. Don't worry -- making modules is not hard at all. See perlmod.
      See perlmod.

      You know, I'm not sure I would send someone to that who just said he's new to Perl. It is lengthy, relates almost entirely to package namespaces with very little discussion of how to actually create a module, and is a great deal more technical than would be required to get started.

Re: calling a perl file from a perl script
by Joost (Canon) on Apr 06, 2007 at 20:46 UTC
    As mentioned above, you can use do "filename" to do what include() does for PHP. However, though it may make some kind of sense in PHP, it is usually not what you want when you're writing programs instead of combining template fragments.

    Consider that do() will compile and execute all the code in the included file each time you run it call do(). This is not how you normally work when you're structuring your program accross multiple files. Generally, you want to structure your program so that functions and classes are grouped logically. You normally don't have your "main function" running over multiple files.

    But functions and classes only need to be defined once. Now consider that you might want to use the functions defined in file "stuff.pl" from the the files "foo.pl" and "bar.pl". The logical way to state that dependency is to "include" the "stuff.pl" in both "foo.pl" and "bar.pl". But if "foo.pl" and "bar.pl" are both needed for your main program, you're including "stuff.pl" twice.

    That's where perl's require("filename") function comes in to play. require() will only load and execute the speficied file the first time you call it. Subsequent calls to require() with the same file-path will do nothing, so it's safe to require the same dependencies in multiple files. For error checking, require() will die if the included file does not end with (returns) a true value.

    Then there's the use Module::Name directive that works like require() but use() will load and execute the file as soon as possible (at compile time), it doesn't take a file path as an argument, but a package name or module that gets converted to a file path, and then tries to call the module's import() method if it exists. **

    Just like require(), all files will only be loaded once, but for each call to use() the package's import() method will be called. That way a module can take additional arguments at load time and possibly modify the caller. Modules using Exporter for instance can introduce variables and function into the calling package without knowing up-front which packages will be using them.

    ** update: you can also specify a Module::Name as an argument to require() but only use() will load at compile time and call the import() method. The biggest advantage of using a module name is that you don't have to specify the exact file path of the module - perl will search for the module in a predefined set of directories, which you can add to with the use lib '/path/' statement if you need to.

Re: calling a perl file from a perl script
by jonadab (Parson) on Apr 06, 2007 at 19:45 UTC
    I am pretty new to perl and this might be a stupid question

    Actually, if anything, the question is probably harder to answer than it needs to be, because of the confusing way in which you stated it. Nonetheless, I'll try...

    how can i separate my code in pieces and run them all from one file

    There are several ways to go about this, depending on what it is you want to accomplish. do '/path/to/filename.pl' for instance is not entirely the same as require '/path/to/filename.pl'. (One difference is that the latter won't run the contents of the file twice if you have the same require statement in two different places.) For a beginner, require may be close to what you want, but it's hard to be sure without knowing more about your situation. Be aware that the required file should finish with a true value. There is also use, of course, not to mention various more obscure possibilities (such as open FOO, $filename and eval scalar <FOO>).

    -- 
    We're working on a six-year set of freely redistributable Vacation Bible School materials.
      well i am creating a crawler that gets product prices and compares them with each other I thought it would be good if I have separate file for each part of my code like to get a link list of the categories one code and for getting a link list of the products one and so on.
        I thought it would be good if I have separate file for each part of my code like to get a link list of the categories one code and for getting a link list of the products one and so on

        That almost sounds like modules. I think I'd recommend creating your functions to do those things you describe in one or more .pm files ("modules"), placing them in one of the site-perl directories listed in @INC, and then loading them with use from any program that wants to use them.

        Modules you're only going to use locally don't have to be held up to the same exacting standards you would do if you were going to publish them to the CPAN for the world to use. A module that's only going to be used by just one app is not really significantly harder to create than any other Perl script. You don't have to mess with package namespaces, for instance, especially for a small application: you can just define your functions in the normal way and let them live in the main namespace. You don't need any more POD for a module of this kind than you would for any other code. I do recommend the use strict pragma, but I'd recommend that even for files you were going to require.

        -- 
        We're working on a six-year set of freely redistributable Vacation Bible School materials.
        Ok, here is one of the more obscure methods of doing that I think. One that I would have used long ago if I had know how to. You can store your code in files as anonymous subs. You might take a look at Perl POE for examples. http://poe.perl.org On the POE site there is an example job server you can pass code_refs to, which would work with this. Then you can load your code from where ever into a hash so you can use a dispatch table. Found this bit on some node on PM here recently.
        my %dispatch_table = ( some_name_one => \&do_something, some_name_two +=> \&do_something_else ); ($dispatch_table{"$some_name"} || sub { print "no command found\n" })- +>($my_args,@into_sub);
        Here is an example of a plugin loader I'm working on for a IRC Bot.
        # the code is loaded into $code from a DB in my case # and it loops around the sub below to load all plugins. # In your file you would have an anonymous sub routine # like { my $times=shift; for (1...$times) { print "Hello, World!\n"; +} } # check reference type my $eval_code = sub { $code }; my $chk_ref=ref $eval_code; if ($chk_ref !~ /CODE/) { print "[load_plugins] Error loading plugin $name: Not CODE!\n"; } else { # test code $eval_code = eval "sub { $code }"; } if ($@) { chomp($@); print "[load_plugins] Error loading plugin $name: $@\n"; } else { # store code in a hash $code{$name} = ( { id => $id, name => $name, code => $eval_code, }, ); print "[load_plugins] Plugin $name loaded successfully.\n"; }
Re: calling a perl file from a perl script
by j3 (Friar) on Apr 06, 2007 at 20:37 UTC

    Hi hodashirzad,

    As jonadab says, writing your own modules is very likely the way to go. Happily, with Perl, easy things tend to be easy, and writing modules (i.e., sticking your functions in .pm files) is a walk in the park. :)

    I believe many folks create their own ~/perllib directory, and drop their modules (ex. MyModule.pm) in there. In your main script code, you tell perl how to find them by putting use lib '/home/you/perllib'; at the top (before the use MyModule; line).

    Edit: To get started, have a look in the Tutorials section of this site, paying special attention to Simple Module Tutorial.

Re: calling a perl file from a perl script
by swampyankee (Parson) on Apr 09, 2007 at 19:04 UTC

    I would not call your question "stupid."

    I will, however, chime in with the chorus singing "use a module." Modules, as I'm sure you know, are Perl's (approximate) equivalent of what are called "libraries" in most compiled languages.

    Now, before doing this kind of work, it's probably wise to poke around CPAN or PPM to see if somebody has already written a module for what you're doing. If not, one could find a module doing something similar and use it for inspiration, giving proper credit to the creator of the module you're plagiarizing using as a muse.

    emc

    Insisting on perfect safety is for people who don't have the balls to live in the real world.

    —Mary Shafer, NASA Dryden Flight Research Center
      Hi,I just wan to know that if 2 pm files are used in a script then i have to call both pm file in pl file so how it is possible.
        Your question did not parse. Did you already read perlmod? use? require?
        []s, HTH, Massa (κς,πμ,πλ)

        It sounds like you're asking how to use two different modules. That's as simple as using two use statements. e.g.

        use strict; use warnings; use Newmodule; use Othermodule;