2017-06-19 17 views
-1

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

爲什麼使用Text :: Autoformat;?你的代碼不使用它。你想用它嗎? – toolic

+0

[Text :: Wrap](http://search.cpan.org/perldoc?Text::Wrap) – ikegami

回答

3

您沒有輸出,因爲您沒有輸入。

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

<$file>操作線1是在列表環境「消耗」所有的輸入,並將其裝入@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); 
    ... 
} 

如果輸入很大,前者格式具有的只是加載的優勢一次一條線進入內存。

+2

由於'truncate'是一個perl內建函數,'&sigil'是許多方法之一(因爲它是Perl)抑制'Ambiguous call resolved CORE :: truncate ...'消息。 OP特此警告[避免使用'&'sigil](https://metacpan.org/pod/Perl::Critic::Policy::Subroutines::ProhibitAmpersandSigils), [謹慎使用原型](https:/ /metacpan.org/pod/Perl::Critic::Policy::Subroutines::ProhibitSubroutinePrototypes)和[不使用與內置Perl函數相同的子例程名稱](https://metacpan.org/pod/Perl ::評論家::策略::子程序:: ProhibitBuiltinHomonyms)。 – mob

相關問題