什么是“最快、最有效的方式”可能是一个不同的问题。这是执行此类操作的典型方法:
use strict;
use warnings;
local $/ = ",";
my @file = <DATA>;
say "Number of records: " . @file;
my $half = int((@file/2)+0.5);
say "Last half of records ($half):";
say @file[$half .. $#file];
__DATA__
20121130092403000Server1::RedHat 1.2.3.4(1234),20121130092503000Server2::RedHat 5.6.7.8(1234),20121130092603000Server3::SUSE 9.8.7.6(9876),20121130092703000Server4::WindowsXP 5.6.7.8(6543),
请注意,此处使用 DATA 文件句柄进行演示。您可以简单地更改<DATA>为<>使其使用文件参数。
这会稍微降低效率,因为文件被读入内存,并且会消耗内存,这对于大文件来说可能是昂贵的。另一种方法是简单地运行文件并计算记录,然后重新打开文件进行打印。例如:
my $file = shift;
local $/ = ",";
open my $fh, "<", $file or die $!;
my $count;
while (<$fh>) { $count++ }
$count = int(($count/2)+0.5);
open $fh, "<", $file or die $!;
while ($count-- > 0) { <$fh> };
while (<$fh>) { print }
当然,这些输出需要重定向,例如:
perl script.pl oldfile > newfile
您可能还喜欢该Tie::File模块。例如:
use strict;
use warnings;
use Tie::File;
my $file = shift;
tie @array, 'Tie::File', $file or die $!;
my $half = int((@array/2)+0.5);
splice @array, 0, $half;
untie @array;
请注意,这样做的影响是不可逆的,因此请在尝试之前进行备份。即使对于大文件,它也被认为是有效的,并且不会将文件读入内存。