简体   繁体   English

在Perl中分割4个空格

[英]Split 4 Spaces in Perl

I have a file which consists of lines in the following format: 我有一个文件,其中包含以下格式的行:

field1    field2    field3

Each field is separated by 4 spaces. 每个字段由4个空格分隔。

I am trying to extract field2 from the above list using Perl. 我正在尝试使用Perl从上面的列表中提取field2。

So, this is what I have done, 所以,这就是我所做的

#! /usr/bin/perl

($input, $output) = @ARGV;

chomp $output;

open(INPUT,"<",$input);
open(OUTPUT,">>",$output);

while(<INPUT>)
{
chomp $_;
($f1,$f2,$f3)= split("\t",$_,3); // *** This line was modified later.
print OUTPUT $f2."\n";
}

close INPUT;
close OUTPUT;

This gives me a blank file. 这给了我一个空白文件。

I have tried to modify the line indicated above with an asterisk as: 我试图将上面带有星号的行修改为:

($f1,$f2,$f3)= split("\t",$_);
($f1,$f2,$f3)= split("    ",$_);
($f1,$f2,$f3)= split("\s\s\s\s",$_);

In all these cases, again I get an empty file. 在所有这些情况下,我再次得到一个空文件。

It may be that your open statement(s) have failed. 您的公开声明可能失败了。 You should never use open without checking if it failed or not, eg 如果不检查open是否失败,则永远不要使用open,例如

open my $fh, '<', $file or die $!;

I used three argument open with a lexical file handle, as is recommended. 按照建议,我使用了三个带有词法文件句柄的参数。 See perldoc -f open for more information. 有关更多信息,请参见perldoc -f open

Such a mistake will be revealed if you are using use warnings , giving an error: 如果使用use warnings ,则会显示此类错误,并给出错误:

readline() on closed filehandle INPUT at ...

However, if you are not using warnings, the error will be silent and deadly. 但是,如果您不使用警告,则错误将是无声的和致命的。 It goes without saying that you should of course always 不用说,您当然应该始终

use warnings;
use strict;

Your code works if the fields are separated by four spaces as you claim. 如果您要求的字段之间用四个空格隔开,则您的代码有效。

$ echo 'field1    field2    field3' | perl -nlE'say for split "    ";'
field1
field2
field3

Verify that your file actually four spaces contains using od -c . 使用od -c验证文件中实际上包含四个空格。


Btw, you're lying to yourself by using split "..." instead of split /.../ . 顺便说一句,您在使用split "..."而不是split /.../来自欺欺人。 The first arg of split is a regular expression. split的第一个arg是一个正则表达式。 It's clearer if you make it look like one. 如果您使它看起来像一个,那就更清楚了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM