我試圖在保留整個單詞的同時將文件的每一行縮短爲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