How do you create a Perl module?

后端 未结 8 1842
醉话见心
醉话见心 2020-12-13 21:03

How do you write a module for Perl? In Python you can use:

# module.py
def helloworld(name):
    print \"Hello, %s\" % name

# main.py
import module
module.         


        
8条回答
  •  失恋的感觉
    2020-12-13 21:11

    Basically you create a file named Yourmodulename.pm, whose contents are:

    package Yourmodulename;
    
    # Here are your definitions
    
    1; # Important, every module should return a true value
    

    Then the program that uses the module will look like:

    #!/usr/bin/perl
    use strict;            # These are good pragmas
    use warnings;      
    
    # Used modules
    use Carp;              # A module that you'll probably find useful
    use Yourmodulename;    # Your module
    

    You may want to organize your modules in a hierarchical (and hopefully logical) way. To do so you create a tree of directories like:

    Your/Module.pm
    Your/Other/Module.pm

    And then in your program:

    use Your::Module;
    use Your::Other::Module;
    

    There are more facilities to export functions and variables from your module, you can take a look at Henning Koch's "Writing serious Perl: The absolute minimum you need to know".

提交回复
热议问题