将空间替换为0

时间:2018-08-17 18:40:27

标签: perl substitution

使用Perl,我只想将空格替换为0。空格由制表符(\ t)分隔。提前致谢!例如:

1   2           2       5               4
4   4   4           4               3   
        4   4           1               
    1   5   6       4                   

收件人

1    2    0    0    2    0    5    0    0    0    4
4    4    4    0    0    4    0    0    0    3    0
0    0    4    4    0    0    1    0    0    0    0
0    1    5    6    0    4    0    0    0    0    0

我的代码:

use strict;
use warnings;
open(DATA,"DATA")||die"cannot open the file: $!\n";


while( <DATA> )
  {
  s/(^|    \K)(?!\d)/0/g;
  print;
  }

结果出来:

1   2           2       5               4
4   4   4           4               3   
0       4   4           1               
0   1   5   6       4                   

2 个答案:

答案 0 :(得分:2)

use strict;
use warnings qw( all );
use feature qw( say );

while (<>) {
   chomp;
   my @fields = split(/\t/, $_, -1);
   for my $field (@fields) {
      $field = 0 if $field eq "";
   }

   say join "\t", @fields;
}

您不清楚“空间”是什么意思。以上将 empty 字段替换为零。选择以下最合适的东西:

  • if $field eq ""(空)
  • if $field eq " "(1个空格)
  • if $field =~ /^[ ]+\z/(超过1个空格)
  • if $field =~ /^[ ]*\z/(0个以上空格)
  • if $field =~ /^\s+\z/(1个以上空格)
  • if $field =~ /^\s*\z/(0 +空格)

答案 1 :(得分:2)

非常容易, 只需将文件内容存储在变量$ x中,然后找到匹配项并替换:

use strict;
use warnings;
my $filename = "c:\path\to\file.txt";
my $x;
    open(my $fh, '<', $filename) or die "cannot open file $filename: $!";
    {
        local $/;
        $x= <$fh>;
    }
    close($fh);


$x=~s/(\n )/\n0/g;      #starting zeros
$x=~s/( \n)/ 0\n/g;     #ending zeros
$x=~s/( $)/ 0\n/g;      #last zero if no end line on end of string
$x=~s/(^ )/0/g;         #first zero at beginning of string
$x=~s/(    )/   0/g;    #zeros within the matrix

print $x;