读取具有固定大小列的文件
Reading a file with fixed size column
使用 perl CGI 我正在尝试从具有固定宽度列的文件中读取并将每个列值插入到数组中。
我想每行读取一个文件,然后用 substr 提取每一列。
列数是固定的,每列都有不同的宽度,space 总是分隔 2 列,但空白 space 也用于列值内部,例如下面的示例(4 列)
this is filed1 field2 this is nextfield3 field4
line2field1 l2field2 field3 and field4 line2
first field second third fourth
问题是当我读取文件时,多个 space 自动被单个 space 替换,请参见下面的示例
#!/usr/bin/perl
use strict;
use diagnostics;
use warnings;
my $file="example.txt";
open(my $fh, '<:encoding(UTF-8)', $file) or die "Could not open file '$file' $!";
while (my $ll =<$fh>) {
print "<br>line is $ll";
}
close $fh;
这个(假设example.txt是上面那个)的输出是:
this is filed1 field2 this is nextfield3 field4
line2field1 l2field2 field3 and field4 line2
first field second third fourth
这并不能真正让我使用 substr 来使用已知的固定宽度来操作字符串。
知道为什么会发生这种情况以及如何读取文件以在字段之间保留额外的 spaced 吗?
我还用 notepad++ 等文本编辑器打开文件,以确保额外的 space 不是由于特殊字符引起的,我可以确认它们只是空白 spaces.
space 仍然存在,但它们被浏览器呈现为一个 space。使用 <pre>
完全按照输入显示它们。
使用 perl CGI 我正在尝试从具有固定宽度列的文件中读取并将每个列值插入到数组中。 我想每行读取一个文件,然后用 substr 提取每一列。 列数是固定的,每列都有不同的宽度,space 总是分隔 2 列,但空白 space 也用于列值内部,例如下面的示例(4 列)
this is filed1 field2 this is nextfield3 field4
line2field1 l2field2 field3 and field4 line2
first field second third fourth
问题是当我读取文件时,多个 space 自动被单个 space 替换,请参见下面的示例
#!/usr/bin/perl
use strict;
use diagnostics;
use warnings;
my $file="example.txt";
open(my $fh, '<:encoding(UTF-8)', $file) or die "Could not open file '$file' $!";
while (my $ll =<$fh>) {
print "<br>line is $ll";
}
close $fh;
这个(假设example.txt是上面那个)的输出是:
this is filed1 field2 this is nextfield3 field4
line2field1 l2field2 field3 and field4 line2
first field second third fourth
这并不能真正让我使用 substr 来使用已知的固定宽度来操作字符串。 知道为什么会发生这种情况以及如何读取文件以在字段之间保留额外的 spaced 吗? 我还用 notepad++ 等文本编辑器打开文件,以确保额外的 space 不是由于特殊字符引起的,我可以确认它们只是空白 spaces.
space 仍然存在,但它们被浏览器呈现为一个 space。使用 <pre>
完全按照输入显示它们。