一、Perl语言简介
Perl(Practical Extraction and Reporting Language)是一种功能强大的脚本语言,特别擅长文本处理。
二、基础语法
1. Hello World
#!/usr/bin/perl
use strict; # 启用严格模式
use warnings; # 启用警告
print "Hello, World!\n";
2. 变量
# 标量(以$开头)
my $name = "Alice";
my $age = 25;
my $price = 99.99;
# 数组(以@开头)
my @fruits = ("apple", "banana", "orange");
my $first_fruit = $fruits[0]; # 访问数组元素
# 哈希(以%开头)
my %person = (
name => "Bob",
age => 30,
city => "Beijing"
);
my $person_name = $person{name}; # 访问哈希值
3. 控制结构
# 条件判断
if ($age > 18) {
print "Adult\n";
} elsif ($age > 12) {
print "Teenager\n";
} else {
print "Child\n";
}
# 循环
for my $i (1..10) {
print "$i ";
}
my $count = 0;
while ($count < 5) {
print $count++;
}
foreach my $fruit (@fruits) {
print "I like $fruit\n";
}
三、实用示例
示例1:文件处理
#!/usr/bin/perl
use strict;
use warnings;
# 读取文件
open my $fh, '<', 'input.txt' or die "Cannot open file: $!";
while (my $line = <$fh>) {
chomp $line; # 移除换行符
print "Line: $line\n";
}
close $fh;
# 写入文件
open my $out_fh, '>', 'output.txt' or die "Cannot create file: $!";
print $out_fh "This is line 1\n";
print $out_fh "This is line 2\n";
close $out_fh;
示例2:文本处理(正则表达式)
#!/usr/bin/perl
use strict;
use warnings;
my $text = "Email: user@example.com, Phone: 138-0013-8000";
# 提取邮箱
if ($text =~ /([\w\.-]+@[\w\.-]+\.\w+)/) {
print "Found email: $1\n";
}
# 提取电话号码
while ($text =~ /(\d{3}-\d{4}-\d{4})/g) {
print "Found phone: $1\n";
}
# 替换文本
$text =~ s/example\.com/test\.com/g;
print "Modified text: $text\n";
示例3:解析日志文件
#!/usr/bin/perl
use strict;
use warnings;
my %ip_count;
open my $log, '<', 'access.log' or die $!;
while (my $line = <$log>) {
# 解析Apache/Nginx访问日志
if ($line =~ /^(\d+\.\d+\.\d+\.\d+)/) {
$ip_count{$1}++;
}
}
close $log;
# 输出IP访问统计
foreach my $ip (sort { $ip_count{$b} <=> $ip_count{$a} } keys %ip_count) {
printf "%-15s: %d\n", $ip, $ip_count{$ip};
}
示例4:CSV文件处理
#!/usr/bin/perl
use strict;
use warnings;
# 简单CSV解析
open my $csv, '<', 'data.csv' or die $!;
while (my $line = <$csv>) {
chomp $line;
my @fields = split /,/, $line;
print "Row: ";
foreach my $field (@fields) {
print "[$field] ";
}
print "\n";
}
close $csv;
示例5:网页内容提取
#!/usr/bin/perl
use strict;
use warnings;
use LWP::Simple; # 需要安装LWP模块
# 获取网页内容
my $url = 'http://example.com';
my $content = get($url) or die "Cannot get $url";
# 提取所有链接
my @links = $content =~ /<a\s+href=["']([^"']+)["']/gi;
print "Found links:\n";
foreach my $link (@links) {
print "$link\n";
}
四、常用模块
# 日期时间
use DateTime;
# JSON处理
use JSON;
# 数据库连接
use DBI;
# 命令行参数
use Getopt::Long;
# XML解析
use XML::Simple;
五、Perl单行命令(实用技巧)
# 替换文件中的文本
perl -pi -e 's/old/new/g' file.txt
# 提取特定列
perl -ane 'print "$F[0]\t$F[2]\n"' data.txt
# 统计行数/单词数
perl -lne '$lines++; $words += scalar(split); END { print "Lines: $lines, Words: $words" }' file.txt
# 文件去重
perl -ne 'print unless $seen{$_}++' file.txt
六、学习资源
官方文档:https://www.perl.org/
CPAN:Perl模块库(https://metacpan.org/)
书籍:
- 《Learning Perl》(小骆驼书)
- 《Intermediate Perl》(羊驼书)
- 《Programming Perl》(大骆驼书)
七、最佳实践
总是使用严格模式
use strict;
use warnings;
使用词法变量
my $variable; # 好
$variable; # 避免使用全局变量
错误处理
open my $fh, '<', $filename or die "Cannot open $filename: $!";
代码注释
# 使用清晰的注释
=pod
多行注释
用于函数说明
=cut
Perl的学习曲线初期可能较陡,但一旦掌握,它在文本处理、系统管理、网络编程等方面非常高效。建议从实际的小项目开始练习,比如日志分析、数据转换等任务。