截断文件中的所有行,同时保留整个单词

时间:2017-06-19 15:23:02

标签: perl foreach while-loop truncate truncated

我试图将文件的每一行缩短为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);

1 个答案:

答案 0 :(得分:3)

您没有输出,因为您没有输入。

1. my @file = <$file>;  #each line of the file into an array
2. while (my $line = <$file>) { ...

<$file>操作行1在列表上下文中#34;消费&#34;所有输入并将其加载到@file。第2行中的<$file>操作没有更多要读取的输入,因此while循环不会执行。

您要么从文件句柄流

# don't call @file = <$file>
while (my $line = <$file>) {
    chomp $line; 
    my $truncated = &truncate($line, 96);
    ...
}

或从文件内容数组中读取

my @file = <$file>;
foreach my $line (@file) {
    chomp $line; 
    my $truncated = &truncate($line, 96);
    ...
}

如果输入很大,前一种格式的优点是一次只能将一行加载到内存中。