【发布时间】:2018-09-26 21:03:16
【问题描述】:
我知道 Perl 中有几个截断示例,但是对于这个代码目标,我还没有找到截断具有 3 列的文本文件的解决方案。
我的目标是仅在读取和写入文本文件时使用 PERL 将文本文件上的 3 列截断为 4 个字符。
我的 INPUT 文本文件 - input.txt:[列号 1,2,3,仅供参考]
1 2 3
Rain 65.22 London
Snow 34.44 United States
Cloudy 23.00 Germany
文本文件不是制表符分隔的,只有空格。
我想要的OUTPUT文件——output.txt:
1 2 3
Rain 65.2 Lond
Snow 34.4 Unit
Clou 23.0 Germ
显示的是我的 output.txt:
Rain Snow Cloudy
这是我的代码:
#!/usr/bin/perl
use strict;
use warnings;
my $input = 'input.txt';
#open file for reading
open my $fhIn, '<', $input or die qq(Unable to open "$input" for input: $!);
#open file for writing
my $output = 'output.txt';
open my $fhOut, '>', $output or die "Can't create output.\n";
while( <$fhIn>) {
(s/.{4}\K.*//s);
print $fhOut $_;
}
【问题讨论】:
标签: perl io truncation