【发布时间】:2017-06-19 15:23:02
【问题描述】:
我正在尝试将文件的每一行缩短为 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);
【问题讨论】:
标签: perl foreach while-loop truncate truncated