上次笔记中的Perl程序在读取文件时是一行一行读入的,作者猜想应该比较慢。今天作者试图提高文件读取的速度。
因为Perl允许将文件内容全部读入到一个数组变量中,所以作者将上次的程序修改如下:
#!/usr/bin/perl -w
# Usage: fjoin.pl <dir>
# This program print all .cpp/.h files in <dir> to stdout
use 5.010;
use strict;
use warnings;
# Sub: print a file to stdout
# Arguments:
# $_[0] The file name
sub printFile
{
my $success = open FHANDLE, "<", $_[0];
my @lines;
if(! $success)
{
return;
}
@lines = <FHANDLE>;
close FHANDLE;
foreach (@lines)
{
print $_;
}
#if(@lines)
#{
# If the last line doesn't end with a LF, append one.
#if(!($lines[@lines - 1] =~ //n$/))
#{
#print "/n";
#}
#}
}
# The main program
my $dir = $ARGV[0];
my @allFiles;
my $file;
if(!defined($dir))
{
die "Directory not defined";
}
# Iterate all files in the dir
@allFiles = <$dir/*>;
if(! @allFiles)
{
die "Can not open the directory $dir";
}
foreach $file (@allFiles)
{
if($file =~ //.cpp$/)
{
&printFile($file);
}
elsif($file =~ //.h$/)
{
&printFile($file);
}
}
但是运行结果却反而比上次的更慢,耗时0.608秒。
具体原因是什么,有待后续研究。