Perl 语言

精选 Perl 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。

#🚀 入门指引

#Unix/Linux 安装 (Unix and Linux Installation)

  • 打开浏览器访问 https://www.perl.org/get.html。

  • 按链接下载适用于 Unix/Linux 的压缩源码包。

  • 下载 perl-5.x.y.tar.gz,并在 $ 提示符下执行以下命令。

$tar -xzf perl-5.x.y.tar.gz
$cd perl-5.x.y
$./Configure -de
$make
$make test
$make install

#🪟 窗口管理 安装 (Windows Installation)

  • Windows 可按链接安装 Strawberry Perl:http://strawberryperl.com

  • 下载 32 位或 64 位安装包。

  • 在资源管理器中双击下载的安装文件,打开 Perl 安装向导; 操作很简单:接受默认设置,等待安装完成即可开始使用。

#Macintosh 安装 (Macintosh Installation)

  • 打开浏览器访问 https://www.perl.org/get.html。

  • 按链接下载适用于 Mac OS X 的压缩源码包。

  • 下载 perl-5.x.y.tar.gz,并在 $ 提示符下执行以下命令

$tar -xzf perl-5.x.y.tar.gz
$cd perl-5.x.y
$./Configure -de
$make
$make test
$make install

#运行 Perl (Running Perl)

# Unix/Linux
$perl  -e <perl code>
# Windows/DOS
C:>perl -e <perl code>

#可用命令行选项 (Available command line options)

选项 (Option) 说明 (Description)
-d[:debugger] 在调试器下运行程序
-Idirectory 指定 @INC/#include 目录
-T 启用污点检查警告
-U 允许不安全操作
-w 启用多项实用警告
-W 启用全部警告
-X 禁用全部警告
-e program 将参数作为 Perl 脚本运行
file 从指定文件运行 Perl 脚本

#从命令行运行脚本 (Script from the Command-line)

# Unix/Linux
$perl  script.pl
# Windows/DOS
C:>perl script.pl

#第一个 Perl 程序 (First Perl Program)

$perl -e 'print "Hello World\n"'

# #!/usr/bin/perl

# This will print "Hello, World"
print "Hello, world\n";
$chmod 0755 hello.pl
$./hello.pl

#Perl 注释 (Comments in Perl)

# This is a comment in perl
=begin comment
This is all part of multiline comment.
You can use as many lines as you like
These comments will be ignored by the
compiler until the next =cut is encountered.
=cut

#Perl 空白字符 (Whitespaces in Perl)

#!/usr/bin/perl

# This would print with a line break in the middle
print "Hello
          world\n";
#output
#Hello
#world

#Perl 单引号与双引号 (Single and Double Quotes in Perl)

#!/usr/bin/perl

print "Hello, world\n";
print 'Hello, world\n';

#Hello, world
#Hello, world\n$

#数据类型

#创建变量 (Creating Variables)

$age = 25;             # An integer assignment
$name = "John Paul";   # A string
$salary = 1445.50;     # A floating point

#标量变量 (Scalar Variables)

#!/usr/bin/perl

$age = 25;             # An integer assignment
$name = "John Paul";   # A string
$salary = 1445.50;     # A floating point

print "Age = $age\n";
print "Name = $name\n";
print "Salary = $salary\n";

#数组变量 (Array Variables)

#!/usr/bin/perl

@ages = (25, 30, 40);
@names = ("John Paul", "Lisa", "Kumar");

print "\$ages[0] = $ages[0]\n";
print "\$ages[1] = $ages[1]\n";
print "\$ages[2] = $ages[2]\n";
print "\$names[0] = $names[0]\n";
print "\$names[1] = $names[1]\n";
print "\$names[2] = $names[2]\n";

#哈希变量 (Hash Variables)

#!/usr/bin/perl

%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);

print "\$data{'John Paul'} = $data{'John Paul'}\n";
print "\$data{'Lisa'} = $data{'Lisa'}\n";
print "\$data{'Kumar'} = $data{'Kumar'}\n";

#变量上下文 (Variable Context)

#!/usr/bin/perl

@names = ('John Paul', 'Lisa', 'Kumar');

@copy = @names;
$size = @names;

print "Given names are : @copy\n";
print "Number of names are : $size\n";

#数值标量 (Numeric Scalars)

#!/usr/bin/perl

$integer = 200;
$negative = -300;
$floating = 200.340;
$bigfloat = -1.2E-23;

# 377 octal, same as 255 decimal
$octal = 0377;

# FF hex, also 255 decimal
$hexa = 0xff;

print "integer = $integer\n";
print "negative = $negative\n";
print "floating = $floating\n";
print "bigfloat = $bigfloat\n";
print "octal = $octal\n";
print "hexa = $hexa\n";

#字符串标量 (String Scalars)

#!/usr/bin/perl

$var = "This is string scalar!";
$quote = 'I m inside single quote - $var';
$double = "This is inside single quote - $var";

$escape = "This example of escape -\tHello, World!";

print "var = $var\n";
print "quote = $quote\n";
print "double = $double\n";
print "escape = $escape\n";

#标量运算 (Scalar Operations)

#!/usr/bin/perl

$str = "hello" . "world";       # Concatenates strings.
$num = 5 + 10;                  # adds two numbers.
$mul = 4 * 5;                   # multiplies two numbers.
$mix = $str . $num;             # concatenates string and number.

print "str = $str\n";
print "num = $num\n";
print "mul = $mul\n";
print "mix = $mix\n";

#多行字符串 (Multiline Strings)

#!/usr/bin/perl

$string = 'This is
a multiline
string';

print "$string\n";


print <<EOF;
This is
a multiline
string
EOF

#V-字符串 (V-Strings)

#!/usr/bin/perl

$smile  = v9786;
$foo    = v102.111.111;
$martin = v77.97.114.116.105.110;

print "smile = $smile\n";
print "foo = $foo\n";
print "martin = $martin\n";

#特殊字面量 (Special Literals)

#!/usr/bin/perl

print "File name ". __FILE__ . "\n";
print "Line Number " . __LINE__ ."\n";
print "Package " . __PACKAGE__ ."\n";

# they can not be interpolated
print "__FILE__ __LINE__ __PACKAGE__\n";

#连续数字数组 (Sequential Number Arrays)

#!/usr/bin/perl

@var_10 = (1..10);
@var_20 = (10..20);
@var_abc = (a..z);

print "@var_10\n";   # Prints number from 1 to 10
print "@var_20\n";   # Prints number from 10 to 20
print "@var_abc\n";  # Prints number from a to z

#数组大小 (Array Size)

#!/usr/bin/perl

@array = (1,2,3);
$array[50] = 4;

$size = @array;
$max_index = $#array;

print "Size:  $size\n";
print "Max Index: $max_index\n";

#数组操作

#数组增删元素 (Adding and Removing Elements in Array)

类型 (types) 说明 (Description)
push @ARRAY, LIST 将列表值压入数组末尾。
pop @ARRAY 弹出并返回数组最后一个值。
shift @ARRAY 移出并返回数组第一个值,数组长度减 1,其余元素前移。
unshift @ARRAY, LIST 将列表插入数组开头,并返回新数组元素个数。

#数组操作示例 (Array oparations)

#!/usr/bin/perl

# create a simple array

@coins = ("Quarter","Dime","Nickel");
print "1. \@coins = @coins\n";

# add one element at the end of the array

push(@coins, "Penny");
print "2. \@coins = @coins\n";

# add one element at the beginning of the array

unshift(@coins, "Dollar");
print "3. \@coins = @coins\n";

# remove one element from the last of the array.

pop(@coins);
print "4. \@coins = @coins\n";

# remove one element from the beginning of the array.

shift(@coins);
print "5. \@coins = @coins\n";

#数组切片 (Slicing Array Elements)

#!/usr/bin/perl

@days = qw/Mon Tue Wed Thu Fri Sat Sun/;

@weekdays = @days[3,4,5];

print "@weekdays\n";

#替换数组元素 (Replacing Array Elements)

#!/usr/bin/perl

@nums = (1..20);
print "Before - @nums\n";

splice(@nums, 5, 5, 21..25);
print "After - @nums\n";

#字符串转数组 (Transform Strings to Arrays)

#!/usr/bin/perl

# define Strings

$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";

# transform above strings into arrays.

@string = split('-', $var_string);
@names = split(',', $var_names);

print "$string[3]\n";  # This will print Roses
print "$names[4]\n"; # This will print Michael

#数组转字符串 (Transform Arrays to Strings)

#!/usr/bin/perl

# define Strings
$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";

# transform above strings into arrays.
@string = split('-', $var_string);
@names  = split(',', $var_names);

$string1 = join( '-', @string );
$string2 = join( ',', @names );

print "$string1\n";
print "$string2\n";

#数组排序 (Sorting Arrays)

#!/usr/bin/perl

# define an array
@foods = qw(pizza steak chicken burgers);
print "Before: @foods\n";

# sort this array
@foods = sort(@foods);
print "After: @foods\n";

#特殊变量 $[ (The $[ Special Variable)

#!/usr/bin/perl

# define an array
@foods = qw(pizza steak chicken burgers);
print "Foods: @foods\n";

# Let's reset first index of all the arrays.
$[ = 1;

print "Food at \@foods[1]: $foods[1]\n";
print "Food at \@foods[2]: $foods[2]\n";

#数组合并 (Merging Arrays)

#!/usr/bin/perl

@odd = (1,3,5);
@even = (2, 4, 6);

@numbers = (@odd, @even);

print "numbers = @numbers\n";

#从列表选取元素 (Selecting Elements from Lists)

#!/usr/bin/perl

@list = (5,4,3,2,1)[1..3];

print "Value of list = @list\n";

#访问哈希元素 (Accessing Hash Elements)

#!/usr/bin/perl

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

print "$data{'John Paul'}\n";
print "$data{'Lisa'}\n";
print "$data{'Kumar'}\n";

#提取哈希切片 (Extracting Slices)

#!/uer/bin/perl


%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);

@array = @data{-JohnPaul, -Lisa};

print "Array : @array\n";

#提取键与值 (Extracting Keys and Values)

#!/usr/bin/perl

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

@names = keys %data;

print "$names[0]\n";
print "$names[1]\n";
print "$names[2]\n";

#获取哈希大小 (Getting Hash Size)

#!/usr/bin/perl

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

@keys = keys %data;
$size = @keys;
print "1 - Hash size:  is $size\n";

@values = values %data;
$size = @values;
print "2 - Hash size:  is $size\n";

#哈希增删元素 (Add and Remove Elements in Hashes)

#!/usr/bin/perl

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size:  is $size\n";

# adding an element to the hash;
$data{'Ali'} = 55;
@keys = keys %data;
$size = @keys;
print "2 - Hash size:  is $size\n";

# delete the same element from the hash;
delete $data{'Ali'};
@keys = keys %data;
$size = @keys;
print "3 - Hash size:  is $size\n";

#控制流

#if-else 分支 (if-else)

#!/usr/bin/perl

# Perl program to illustrate
# Decision-Making statements

$a = 10;
$b = 15;

# if condition to check
# for even number
if($a % 2 == 0 )
{
	printf "Even Number";
}

# if-else condition to check
# for even number or odd number
if($b % 2 == 0 )
{
	printf "\nEven Number";
}
else
{
	printf "\nOdd Number";
}

#三元运算符 ?: (The ? : Operator)

#!/usr/local/bin/perl

$name = "Ali";
$age = 10;

$status = ($age > 60 )? "A senior citizen" : "Not a senior citizen";

print "$name is  - $status\n";

#for 循环 (for loop)

#!/usr/bin/perl

# Perl program to illustrate
# the use of for Loop

# for loop
print("For Loop:\n");
for ($count = 1 ; $count <= 3 ; $count++)
{
	print "GeeksForGeeks\n"
}

#foreach 循环 (foreach loop)

#!/usr/bin/perl

# Perl program to illustrate
# the use of foreach Loop

# Array
@data = ('GEEKS', 4, 'GEEKS');

# foreach loop
print("For-each Loop:\n");
foreach $word (@data)
{
	print ("$word ");
}

#while 与 do-while (while and do-while)

#!/usr/bin/perl

# Perl program to illustrate
# the use of foreach Loop

# while loop
$count = 3;

print("While Loop:\n");
while ($count >= 0)
{
	$count = $count - 1;
	print "GeeksForGeeks\n";
}

print("\ndo...while Loop:\n");
$a = 10;

# do..While loop
do {

	print "$a ";
	$a = $a - 1;
} while ($a > 0);

#面向对象编程

#类与对象 (Class and object)

#!/usr/bin/perl

# Perl Program for creation of a
# Class and its object
use strict;
use warnings;

package student;

# constructor
sub student_data
{

	# shift will take package name 'student'
	# and assign it to variable 'class'
	my $class_name = shift;
	my $self = {
				'StudentFirstName' => shift,
				'StudentLastName' => shift
			};
	# Using bless function
	bless $self, $class_name;

	# returning object from constructor
	return $self;
}

# Object creating and constructor calling
my $Data = student_data student("Geeks", "forGeeks");

# Printing the data
print "$Data->{'StudentFirstName'}\n";
print "$Data->{'StudentLastName'}\n";

#子程序 (Subroutines)

#!/usr/bin/perl

# Perl Program to demonstrate the
# subroutine declaration and calling

# defining subroutine
sub ask_user
{
	print "Hello Geeks!\n";
}

# calling subroutine
# you can also use
# &ask_user();
ask_user();

#模块与包 (Modules and Packages)

#!/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);

#引用 (References)

# Perl program to illustrate the
# Referencing and Dereferencing
# of an Array

# defining an array
@array = ('1', '2', '3');

# making an reference to an array variable
$reference_array = \@array;

# Dereferencing
# printing the value stored
# at $reference_array by prefixing
# @ as it is a array reference
print @$reference_array;

#正则表达式 (Regular Expression)

# Perl program to demonstrate
# the m// and =~ operators

# Actual String
$a = "GEEKSFORGEEKS";

# Prints match found if
# its found in $a
if ($a =~ m[GEEKS])
{
	print "Match Found\n";
}

# Prints match not found
# if its not found in $a
else
{
	print "Match Not Found\n";
}

#文件处理 (File Handling)

# Opening the file
open(fh, "GFG2.txt") or die "File '$filename' can't be opened";

# Reading First line from the file
$firstline = <fh>;
print "$firstline\n";

#文件测试运算符 (File Test Operators)

#!/usr/bin/perl

# Using predefined modules
use warnings;
use strict;

# Providing path of file to a variable
my $filename = 'C:\Users\GeeksForGeeks\GFG.txt';

# Checking for the file existence
if(-e $filename)
{

	# If File exists
	print("File $filename exists\n");
}

else
{

	# If File doesn't exists
	print("File $filename does not exists\n");
}

#处理 Excel 文件 (Working with Excel Files)

#!/usr/bin/perl
use Excel::Writer::XLSX;

my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );
my $Excelsheet = $Excelbook->add_worksheet();

$Excelsheet->write( "A1", "Hello!" );
$Excelsheet->write( "A2", "GeeksForGeeks" );
$Excelsheet->write( "B1", "Next_Column" );

$Excelbook->close;

#读取 Excel 文件 (Reading from an Excel File)

use 5.016;
use Spreadsheet::Read qw(ReadData);
my $book_data = ReadData (‘new_excel.xlsx');
say 'A2: ' . $book_data->[1]{A2};

#错误处理 (Error Handling)

if(open(DATA, $file)) {
   ...
} else {
   die "Error: Couldn't open the file - $!"
}
#example
open(DATA, $file) || die "Error: Couldn't open the file $!";
## example
unless(chdir("/etc")) {
   die "Error: Can't change directory - $!";
}
##example
print(exists($hash{value}) ? 'There' : 'Missing',"\n");

#warn 函数 (The warn Function)

chdir('/etc') or warn "Can't change directory";


#die 函数 (The die function)

chdir('/etc') or die "Can't change directory";

#模块内错误 (Errors within Modules)

package T;

require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;

sub function {
   warn "Error in module!";
}
1;
#use T;
#function();
# all below code call the funtion

#carp 函数 (The carp Function)

package T;

require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;

sub function {
   carp "Error in module!";
}
1;

#cluck 函数 (The cluck Function)

package T;

require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp qw(cluck);

sub function {
   cluck "Error in module!";
}
1;

#croak 函数 (The croak Function)

package T;

require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;

sub function {
   croak "Error in module!";
}
1;

#confess 函数 (The confess Function)

package T;

require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;

sub function {
   confess "Error in module!";
}
1;

#日期和时间

#当前日期与时间 (Current Date and Time)

#!/usr/local/bin/perl

@months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
@days = qw(Sun Mon Tue Wed Thu Fri Sat Sun);

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
print "$mday $months[$mon] $days[$wday]\n";
#or
#!/usr/local/bin/perl

$datestring = localtime();
print "Local date and time $datestring\n";

#GMT 时间 (GMT Time)

#!/usr/local/bin/perl

$datestring = gmtime();
print "GMT date and time $datestring\n";

#格式化日期时间 (Format Date and Time)

#!/usr/local/bin/perl

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();

printf("Time Format - HH:MM:SS\n");
printf("%02d:%02d:%02d", $hour, $min, $sec);

#Epoch 时间 (Epoch time)

#!/usr/local/bin/perl

$epoc = time();

print "Number of seconds since Jan 1, 1970 - $epoc\n";
#or
#!/usr/local/bin/perl

$datestring = localtime();
print "Current date and time $datestring\n";

$epoc = time();
$epoc = $epoc - 24 * 60 * 60;   # one day before of current date.

$datestring = localtime($epoc);
print "Yesterday's date and time $datestring\n";

#POSIX 函数 strftime() (POSIX Function strftime())

说明符 (Specifier) 替换为 (Replaced by) 示例 (Example)
%a 星期缩写 Thu
%A 完整星期名 Thursday
%b 月份缩写 Aug
%B 完整月份名 August
%c 日期时间表示 Thu Aug 23 14:55:02 2001
%C 年份除以 100 后取整 (00-99) 20
%d 月份中的日,补零 (01-31) 23
%D 短日期 MM/DD/YY,等价于 %m/%d/%y 08/23/01
%e 月份中的日,空格填充 ( 1-31) 23
%F 短日期 YYYY-MM-DD,等价于 %Y-%m-%d 2001-08-23
%g 周历年份,后两位 (00-99) 01
%G 周历年份 2001
%h 月份缩写(同 %b) Aug
%H 24 小时制小时 (00-23) 14
%I 12 小时制小时 (01-12) 02
%j 一年中的第几天 (001-366) 235
%m 月份数字 (01-12) 08
%M 分钟 (00-59) 55
%n 换行符 ('\n')
%p 上午/下午标记 PM
%r 12 小时制时间 02:55:02 pm
%R 24 小时制 HH:MM,等价于 %H:%M 14:55
%S 秒 (00-61) 02
%t 水平制表符 ('\t')
%T ISO 8601 时间 (HH:MM:SS),等价于 %H:%M:%S 14:55
%u ISO 8601 星期数字,周一为 1 (1-7) 4
%U 周序号(以第一个周日为一周起始)(00-53) 33
%V ISO 8601 周序号 (00-53) 34
%w 星期数字,周日为 0 (0-6) 4
%W 周序号(以第一个周一为一周起始)(00-53) 34
%x 日期表示 08/23/01
%X 时间表示 14:55:02
%y 年份后两位 (00-99) 01
%Y 年份 2001
%z ISO 8601 相对 UTC 的时区偏移(1 分钟=1,1 小时=100);无法确定时区则无输出 +100
%Z 时区名或缩写;无法确定时区则无输出 CDT
%% 百分号 % %
#!/usr/local/bin/perl
use POSIX qw(strftime);

$datestring = strftime "%a %b %e %H:%M:%S %Y", localtime;
printf("date and time - $datestring\n");

# or for GMT formatted appropriately for your locale:
$datestring = strftime "%a %b %e %H:%M:%S %Y", gmtime;
printf("date and time - $datestring\n");