我试图在保留整个单词的同时将文件的每一行缩短为96个字符。如果一行字符小于或等于96个字符,我不想对该行做任何事情。如果它超过96个字符,我希望它在保留整个单词的同时将其缩减到最接近的96个字符。当我运行这段代码时,我得到一个空白文件。截取文件中的所有行,同时保留整个单词
use Text::Autoformat;
use strict;
use warnings;
#open the file
my $filename = $ARGV[0]; # store the 1st argument into the variable
open my $file, '<', $filename;
open my $fileout, '>>', $filename.96;
my @file = <$file>; #each line of the file into an array
while (my $line = <$file>) {
chomp $line;
foreach (@file) {
#######
sub truncate($$) {
my ($line, $max) = @_;
# always do nothing if already short enough
(length($line) <= $max) and return $line;
# forced to chop a word anyway
if ($line =~ /\s/) {
return substr($line, 0, $max);
}
# otherwise truncate on word boundary
$line =~ s/\S+$// and return $line;
die; # unreachable
}
#######
my $truncated = &truncate($line,96);
print $fileout "$truncated\n";
}
}
close($file);
close($fileout);
为什么使用Text :: Autoformat;?你的代码不使用它。你想用它吗? – toolic
[Text :: Wrap](http://search.cpan.org/perldoc?Text::Wrap) – ikegami