【问题标题】:substitute space to 0将空格替换为 0
【发布时间】:2018-08-17 18:40:27
【问题描述】:

使用 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                   

【问题讨论】:

  • 作为空格字符?这是什么语言?
  • 例如 1 和 2 之间的字符是什么?它是一个标签 (\t) 吗?
  • 谢谢,Alan Deep.Yes 选项卡 (\t)。
  • 提示:不要使用DATA;它是现有文件句柄的名称
  • 提示:不要对文件句柄使用全局变量。使用词法变量 (open(my $DATA, ...))

标签: perl substitution


【解决方案1】:

很简单, 只需将文件的内容存储在变量 $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;

【讨论】:

  • @yueli 我从未使用过 perl,但我阅读了文档来回答您的问题。 $filename 应替换为 'temp01'。如果 temp01 位于 C:/ 中,则将 $filename 替换为 'C:/temp01'
  • 您好,Alan Deep,非常感谢您的快速回复。我替换了文件 temp01.但是,它出现了:全局符号“$temp01”需要在 alan.pl 第 4 行显式的包名称。alan.pl 的执行由于编译错误而中止。
  • @yueli 很高兴为您提供帮助!
  • 我想知道可能存在读取文件问题。我试着弄明白。
  • @yueli 你可能会发布另一个问题,因为这将是没有问题的话题。 (社区指南)
【解决方案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+ 空格)

【讨论】:

  • 您好,ikegami,非常感谢您的大力帮助。有效!
  • 没问题。如果这回答了您的问题,请检查它旁边的标记。
  • 添加了一个缺失的chomp
  • 你好,池上。我可以阅读你的代码。我可以问你一个简单的问题吗?为什么 split (/\t/,$_,-1) 中有“-1”?再次感谢您的帮助!
  • 加上chomp就完美了!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 2015-05-25
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多