Perl如何创建和使用模块?代码示例

2021年3月20日14:10:32 发表评论 684 次浏览

Perl中的模块是执行一系列编程任务的相关子例程和变量的集合。 Perl模块是可重用的。综合Perl存档网络(CPAN)上提供了各种Perl模块。这些模块涵盖了广泛的类别, 例如网络, CGI, XML处理, 数据库接口等。

创建一个Perl模块

模块名称必须与软件包名称相同, 并以.pm扩展名结尾。

示例:Calculator.pm

package Calculator;
  
# Defining sub-routine for Multiplication
sub multiplication
{
     # Initializing Variables a & b
     $a = $_ [0];
     $b = $_ [1];
      
     # Performing the operation
     $a = $a * $b ;
      
     # Function to print the Sum
     print "\n***Multiplication is $a" ;
}
  
# Defining sub-routine for Division
sub division
{
     # Initializing Variables a & b
     $a = $_ [0];
     $b = $_ [1];
      
     # Performing the operation
     $a = $a / $b ;
      
     # Function to print the answer
     print "\n***Division is $a" ;
}
1;

在这里, 文件名是存储在目录Calculator中的" Calculator.pm"。注意1;在代码末尾编写, 以将真值返回给解释器。 Perl接受任何真实值, 而不是1

导入和使用Perl模块

要导入此计算器模块, 我们使用require或use函数。要从模块访问函数或变量, 请使用::。这是一个演示相同内容的示例:

示例:Test.pl

#!/usr/bin/perl
  
# Using the Package 'Calculator'
use Calculator;
  
print "Enter two numbers to multiply" ;
  
# Defining values to the variables
$a = 5;
$b = 10;
  
# Subroutine call
Calculator::multiplication( $a , $b );
  
print "\nEnter two numbers to divide" ;
  
# Defining values to the variables
$a = 45;
$b = 5;
  
# Subroutine call
Calculator::division( $a , $b );

输出如下:

Perl 模块1

使用模块中的变量

可以通过在使用之前声明它们来使用来自不同程序包的变量。以下示例说明了这一点

示例:Message.pm

#!/usr/bin/perl
  
package Message;
  
# Variable Creation
$username ;
  
# Defining subroutine
sub Hello
{
   print "Hello $username\n" ;
}
1;

Perl文件访问模块如下

示例:variable.pl

#!/usr/bin/perl
  
# Using Message.pm package
use Message;
  
# Defining value to variable
$Message::username = "Geeks" ;
  
# Subroutine call
Message::Hello();

输出如下:

Perl 模块2

使用预定义的模块

Perl提供了可以在Perl程序中随时使用的各种预定义模块。

例如:"严格", "警告"等。

例子:

#!/usr/bin/perl
  
use strict;
use warnings;
  
print " Hello This program uses Pre-defined Modules" ;

输出如下:

Hello This program uses Pre-defined Modules

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: