Perl编程练习解析与实践
1. 数据发送统计练习
在这个练习中,我们的目标是统计发送到所有机器的数据量。以下是详细的实现步骤和代码:
-
变量初始化
:
my $all = "**all machines**";
这里将
$all
变量设置为一个特殊名称,用于代表所有机器,且这个名称不会用于任何实际机器,方便后续程序编写和修改。
-
输入循环处理
:
my %total_bytes;
while (<>) {
next if /^#/;
my ($source, $destination, $bytes) = split;
$total_bytes{$source}{$destination} += $bytes;
$total_bytes{$source}{$all} += $bytes;
}
此循环会跳过注释行,并对每行数据进行拆分,分别记录源机器到目标机器的字节数以及源机器发送的总字节数。
-
排序与输出
:
my @sources =
sort { $total_bytes{$b}{$all} <=> $total_bytes{$a}{$all} }
keys %total_bytes;
for my $source (@sources) {
my @destinations =
sort { $total_bytes{$source}{$b} <=> $total_bytes{$source}{$a} }
keys %{ $total_bytes{$source} };
print "$source: $total_bytes{$source}{$all} total bytes sent\n";
for my $destination (@destinations) {
next if $destination eq $all;
print " $source => $destination: $total_bytes{$source}{$destination} bytes\n";
}
print "\n";
}
首先对源机器按总发送字节数降序排序,然后对每个源机器的目标机器按接收字节数降序排序并输出。
为了简化代码,我们可以使用一个简单的标量来替代多次使用的
$total_bytes{$source}
:
for my $source (@sources) {
my $tb = $total_bytes{$source};
my @destinations = sort { $tb->{ $b } <=> $tb->{ $a } } keys %$tb;
print "$source: $tb->{ $all } total bytes sent\n";
for my $destination (@destinations) {
next if $destination eq $all;
print " $source => $destination: $tb->{ $destination } bytes\n";
}
print "\n";
}
这样代码会更简洁,且可能会稍微快一些。
2. 数据聚合输出练习
此练习从数据聚合代码开始,然后对聚合后的数据进行输出:
my %total_bytes;
while (<>) {
my ($source, $destination, $bytes) = split;
$total_bytes{$source}{$destination} += $bytes;
}
foreach my $source (sort keys %total_bytes) {
print "$source\n";
my $dest_hash = $total_bytes{$source};
foreach my $dest (sort keys %$dest_hash) {
print " $dest $dest_hash->{ $dest }\n";
}
}
先对每行数据进行聚合,然后按源机器排序,再对每个源机器的目标机器排序并输出。
3. 使用Storable存储数据练习
这个练习与之前类似,但使用了
Storable
模块来存储和读取数据:
use Storable;
my $all = "**all machines**";
my $data_file = "total_bytes.data";
my %total_bytes;
if (-e $data_file) {
my $data = retrieve $data_file;
%total_bytes = %$data;
}
while (<>) {
next if /^#/;
my ($source, $destination, $bytes) = split;
$total_bytes{$source}{$destination} += $bytes;
$total_bytes{$source}{$all} += $bytes;
}
store \%total_bytes, $data_file;
如果数据文件存在,则读取数据,然后对新输入的数据进行处理并更新,最后将数据存储回文件。
4. 使用JSON存储数据练习
若要使用
JSON
代替
Storable
,需要做更多工作:
use JSON;
my $all = "**all machines**";
my $data_file = "total_bytes.json";
my $total_bytes;
if (-e $data_file) {
local $/;
open my $fh, '<:raw', $data_file;
$json_text = <$fh>;
$total_bytes = decode_json($json_text);
}
while (<>) {
next if /^#/;
my ($source, $destination, $bytes) = split;
$total_bytes->{ $source }{ $destination } += $bytes;
$total_bytes->{ $source }{ $all } += $bytes;
}
{
open my $fh, '>:utf8', $data_file;
print $fh to_json($total_bytes, { pretty => 1 });
}
foreach my $source (sort keys %$total_bytes) {
print "$source\n";
my $dest_hash = $total_bytes->{ $source };
foreach my $dest (sort keys %$dest_hash) {
print " $dest $dest_hash->{ $dest }\n";
}
}
首先读取
JSON
文件并解析数据,然后处理新输入的数据,最后将数据以
JSON
格式存储回文件。
5. 文件修改时间筛选练习
此练习需要添加
gather_mtime_between
子例程:
sub gather_mtime_between {
my ($begin, $end) = @_;
my @files;
my $gatherer = sub {
my $timestamp = (stat $_)[9];
unless (defined $timestamp) {
warn "Can't stat $File::Find::name: $!, skipping\n";
return;
}
push @files, $File::Find::name
if $timestamp >= $begin and $timestamp <= $end;
};
my $fetcher = sub { @files };
($gatherer, $fetcher);
}
该子例程用于筛选出修改时间在指定范围内的文件。
6. 不同输出方式练习
这个练习要求使用三种不同的输出方式:输出到文件、输出到标量或同时输出到两者:
use IO::Tee;
use v5.8;
my $fh;
my $scalar;
print 'Enter type of output [Scalar/File/Tee]> ';
my $type = <STDIN>;
if ($type =~ /^s/i) {
open $fh, '>', \$scalar;
}
elsif ($type =~ /^f/i) {
open $fh, '>', "$0.out";
}
elsif ($type =~ /^t/i) {
open my $file_fh, '>', "$0.out"
or die "Could not open $0.out: $!";
open my $scalar_fh, '>', \$scalar;
$fh = IO::Tee->new($file_fh, $scalar_fh);
}
my $date = localtime;
my $day_of_week = (localtime)[6];
print $fh <<"HERE";
This is run $$
The date is $date
The day of the week is $day_of_week
HERE
print STDOUT <<"HERE" if $type =~ m/^[st]/i;
Scalar contains:
$scalar
HERE
程序会根据用户输入的输出类型,将信息输出到相应的位置。
7. 多文件句柄处理练习
此练习需要同时维护多个打开的文件句柄:
my %output_handles;
while (<>) {
unless (/^([^:]+):/) {
warn "ignoring the line with missing name: $_";
next;
}
my $name = lc $1;
unless ($output_handles{$name}) {
open my $fh, '>', "$name.info"
or die "Cannot create $name.info: $!";
$output_handles{$name} = $fh;
}
print { $output_handles{$name} } $_;
}
程序会从每行数据中提取名称,为每个名称创建一个文件句柄并将数据写入相应的文件。
8. 目录处理练习
该练习用于处理目录参数,输出目录内容:
my @not_dirs = grep {! -d } @ARGV;
foreach my $not_dir (@not_dirs) {
print "$not_dir is not a directory!\n";
}
my @dirs = grep { -d } @ARGV;
my @dir_hs = map { opendir my $dh, $_; $dh } grep { -d } @ARGV;
foreach my $dh (@dir_hs) { print_contents($dh) };
sub print_contents {
my $dh = shift;
while (my $file = readdir $dh) {
next if ($file eq '.' or $file eq '..');
print "$file\n";
}
}
首先找出不是目录的参数并输出错误信息,然后对目录参数打开目录句柄并输出目录内容。
9. 正则匹配练习
- 练习1 :
my %patterns = (
Gilligan => qr/(?:Willie )?Gilligan/,
'Mary Ann' => qr/Mary Ann/,
Ginger => qr/Ginger/,
Professor => qr/(?:The )?Professor/,
Skipper => qr/Skipper/,
'A Howell' => qr/Mrs?. Howell/,
);
my $key = rightmost(
'There is Mrs. Howell, Ginger, and Gilligan, Skipper',
\%patterns
);
say "Rightmost character is $key";
sub rightmost {
my ($string, $patterns) = @_;
my ($rightmost_position, $rightmost_key) = (-1, undef);
while (my ($key, $value) = each %$patterns) {
my $position = $string =~ m/$value/ ? $-[0] : -1;
if ($position > $rightmost_position) {
$rightmost_position = $position;
$rightmost_key = $key;
}
}
return $rightmost_key;
}
该练习通过正则表达式匹配找出字符串中最右边匹配的模式。
-
练习2
:
open my $fh, '<', 'patterns.txt'
or die "Could not open patterns.txt: $!";
while (<$fh>) {
chomp;
my $pattern = eval { qr/$_/ }
or do { warn "Invalid pattern: $@"; next };
push @patterns, $pattern;
}
while (<>) {
foreach my $pattern (@patterns) {
print "Match at line $. | $_" if /$pattern/;
}
}
此练习从文件中读取正则表达式模式,然后对输入的每行数据进行匹配并输出匹配信息。
-
练习3
:
use Regexp::Assemble;
open my $fh, '<', 'patterns.txt'
or die "Could not open patterns.txt: $!";
my $ra = Regexp::Assemble->new;
while (<$fh>) {
chomp;
$ra->add($_);
}
my $overall = $ra->re;
print "Regexp is: $overall\n";
while (<>) {
print "Match at line $. | $_" if /$overall/;
}
该练习使用
Regexp::Assemble
模块将多个正则表达式组合成一个整体模式,然后对输入数据进行匹配。
10. 排序与性能测试练习
- 练习1 :
use v5.10;
chdir;
my @sorted =
map $_->[0],
sort { $a->[1] <=> $b->[1] }
map [$_, -s $_],
glob '*';
say join "\n", @sorted;
此练习使用Schwartzian Transform对文件按大小排序。
-
练习2
:
use Benchmark qw(timethese);
chdir;
my @files = glob '*';
print 'There are ' . @files . " files to compare\n";
my $ordinary = sub {
my @sorted = sort { -s $a <=> -s $b } @files;
};
my $transform = sub {
my @sorted =
map $_->[0],
sort { $a->[1] <=> $b->[1] }
map [$_, -s $_],
@files;
};
timethese(-2, {
ordinary => $ordinary,
transform => $transform
});
该练习使用
Benchmark
模块比较普通排序和Schwartzian Transform排序的性能。
以下是一个简单的流程图,展示了数据统计和存储的主要流程:
graph TD;
A[开始] --> B[初始化变量];
B --> C[读取输入数据];
C --> D{是否为注释行};
D -- 是 --> C;
D -- 否 --> E[拆分数据并更新统计];
E --> F{是否有数据文件};
F -- 是 --> G[读取数据文件];
F -- 否 --> H[继续处理数据];
G --> H;
H --> I[存储数据到文件];
I --> J[输出统计结果];
J --> K[结束];
通过以上这些练习,我们可以更深入地理解Perl编程中的数据处理、文件操作、正则表达式匹配、排序和性能测试等方面的知识。在实际应用中,我们可以根据具体需求选择合适的方法和模块来完成任务。同时,我们也可以对代码进行优化,提高程序的性能和可读性。
在后续的编程学习中,我们可以进一步探索这些知识的应用场景,尝试将不同的技术结合起来解决更复杂的问题。例如,在处理大数据集时,我们可以考虑使用更高效的数据结构和算法;在进行性能优化时,我们可以使用更精确的性能测试工具和方法。总之,不断学习和实践是提升编程能力的关键。
Perl编程练习解析与实践
11. 综合应用与拓展思考
在完成上述各项练习后,我们可以思考如何将这些知识进行综合应用,以解决更复杂的实际问题。例如,我们可以结合数据统计、文件存储和正则匹配,对大量的日志文件进行分析。以下是一个简单的示例,展示如何实现这个功能:
use Storable;
use JSON;
use Regexp::Assemble;
# 初始化变量
my $all = "**all machines**";
my $data_file = "total_bytes.data";
my %total_bytes;
# 读取存储的数据
if (-e $data_file) {
my $data = retrieve $data_file;
%total_bytes = %$data;
}
# 读取正则表达式模式文件
open my $fh_patterns, '<', 'patterns.txt'
or die "Could not open patterns.txt: $!";
my $ra = Regexp::Assemble->new;
while (<$fh_patterns>) {
chomp;
$ra->add($_);
}
my $overall_pattern = $ra->re;
# 处理输入的日志文件
while (<>) {
next if /^#/;
my ($source, $destination, $bytes) = split;
$total_bytes{$source}{$destination} += $bytes;
$total_bytes{$source}{$all} += $bytes;
# 正则匹配日志内容
if (/^$overall_pattern/) {
print "Match found in line: $_";
}
}
# 存储更新后的数据
store \%total_bytes, $data_file;
# 输出统计结果
foreach my $source (sort keys %total_bytes) {
print "$source: $total_bytes{$source}{$all} total bytes sent\n";
my @destinations = sort { $total_bytes{$source}{$b} <=> $total_bytes{$source}{$a} } keys %{ $total_bytes{$source} };
for my $destination (@destinations) {
next if $destination eq $all;
print " $source => $destination: $total_bytes{$source}{$destination} bytes\n";
}
print "\n";
}
这个示例程序结合了数据统计、文件存储和正则匹配的功能。首先,它从存储文件中读取之前的统计数据,然后读取正则表达式模式文件并组合成一个整体模式。接着,程序处理输入的日志文件,更新数据统计信息,并对每行日志进行正则匹配。最后,程序将更新后的数据存储回文件,并输出统计结果。
12. 性能优化建议
在实际编程中,性能优化是一个重要的方面。以下是一些针对上述练习和示例代码的性能优化建议:
-
减少重复计算
:在排序和统计过程中,尽量避免重复计算相同的值。例如,在使用
-s函数获取文件大小时,可以将结果缓存起来,避免多次调用。 - 使用更高效的数据结构 :根据具体情况,选择合适的数据结构可以提高程序的性能。例如,在处理大量数据时,哈希表通常比数组更高效。
- 避免不必要的循环 :在编写代码时,尽量减少不必要的循环嵌套,以降低时间复杂度。
-
使用并行处理
:对于一些计算密集型的任务,可以考虑使用并行处理来提高性能。例如,使用
Parallel::ForkManager模块来实现多进程处理。
13. 错误处理与异常情况
在编写程序时,错误处理和异常情况的处理是必不可少的。以下是一些常见的错误处理方法和建议:
-
文件操作错误
:在打开文件时,使用
or die语句来处理文件打开失败的情况。例如:
open my $fh, '<', 'file.txt'
or die "Could not open file.txt: $!";
-
正则表达式错误
:在编译正则表达式时,使用
eval语句来捕获无效的正则表达式。例如:
my $pattern = eval { qr/$_/ }
or do { warn "Invalid pattern: $@"; next };
-
数据存储错误
:在使用
Storable或JSON模块进行数据存储时,检查返回值,确保存储操作成功。例如:
if (!store \%total_bytes, $data_file) {
warn "Failed to store data to $data_file: $!";
}
14. 代码复用与模块化
为了提高代码的可维护性和复用性,我们可以将一些常用的功能封装成函数或模块。以下是一个简单的示例,展示如何将数据统计和输出功能封装成函数:
sub process_data {
my %total_bytes;
while (<>) {
next if /^#/;
my ($source, $destination, $bytes) = split;
$total_bytes{$source}{$destination} += $bytes;
$total_bytes{$source}{$all} += $bytes;
}
return \%total_bytes;
}
sub output_statistics {
my $total_bytes = shift;
foreach my $source (sort keys %$total_bytes) {
print "$source: $total_bytes->{$source}{$all} total bytes sent\n";
my @destinations = sort { $total_bytes->{$source}{$b} <=> $total_bytes->{$source}{$a} } keys %{ $total_bytes->{$source} };
for my $destination (@destinations) {
next if $destination eq $all;
print " $source => $destination: $total_bytes->{$source}{$destination} bytes\n";
}
print "\n";
}
}
# 使用封装的函数
my $total_bytes = process_data();
output_statistics($total_bytes);
通过将功能封装成函数,我们可以在不同的程序中复用这些功能,提高代码的可维护性和复用性。
15. 总结与展望
通过对这些Perl编程练习的深入学习和实践,我们掌握了数据处理、文件操作、正则表达式匹配、排序和性能测试等方面的知识。这些知识在实际编程中具有广泛的应用场景,例如日志分析、数据统计、文件处理等。
在未来的学习和工作中,我们可以进一步探索Perl编程的高级特性和模块,如数据库操作、网络编程、图形界面开发等。同时,我们也可以将Perl与其他编程语言结合使用,发挥不同语言的优势,解决更复杂的问题。
以下是一个总结表格,展示了本文涉及的主要知识点和对应的练习:
| 知识点 | 对应的练习 |
|---|---|
| 数据统计 | 数据发送统计练习、数据聚合输出练习 |
| 文件存储 | 使用Storable存储数据练习、使用JSON存储数据练习 |
| 正则表达式匹配 | 正则匹配练习 |
| 排序与性能测试 | 排序与性能测试练习 |
| 多文件句柄处理 | 多文件句柄处理练习 |
| 目录处理 | 目录处理练习 |
| 不同输出方式 | 不同输出方式练习 |
最后,我们可以用一个流程图来展示整个编程学习和实践的过程:
graph TD;
A[学习基础知识] --> B[完成练习];
B --> C[综合应用与拓展];
C --> D[性能优化];
D --> E[错误处理与模块化];
E --> F[总结与展望];
F --> G[持续学习与实践];
通过不断地学习和实践,我们可以不断提升自己的编程能力,解决更多复杂的实际问题。
Perl编程核心技能实战
超级会员免费看
679

被折叠的 条评论
为什么被折叠?



