How do you create a Perl module?

后端 未结 8 1852
醉话见心
醉话见心 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条回答
  •  旧时难觅i
    2020-12-13 21:10

    One minor detail that the answers so far haven't mentioned is that, if you have a (preferably small) module which is purpose-specific enough that it will never be reused, you can put it into the same file as the main program or another package:

    # main.pl
    
    # Since this is a beginner question, I'll also point out that you should
    # *always* use strict and warnings.  It will save you many headaches.
    use strict;
    use warnings;
    
    MyModule::helloworld('Jim');
    AnotherModule::helloworld('Jim');
    
    package MyModule; # Still in main.pl!
    
    sub helloworld { 
        my ( $name ) = @_;
        print "Hello, $name\n";
    }
    
    package AnotherModule; # Yep, still main.pl
    
    sub helloworld {
        my $name = shift;
        print "Another hello to $name\n";
    }
    

    This isn't used often because it gives you a package that's defined in a file whose name isn't the same as the package's, which can get confusing because you have to use/require the filename, but reference it in code by the package name.

    Also note that the 1; is only needed as the final line of each file which is included via use/require. In this case, I didn't need it because it's in main.pl. If you put multiple packages into the same file, you only need a 1; at the end of the file, not after each package.

提交回复
热议问题