【问题标题】:Perl read and print Line by linePerl 逐行读取和打印
【发布时间】:2014-11-19 16:07:31
【问题描述】:

我正在尝试逐行打印以下内容:

My info


info | info | info |
-------------------------
1    |  1   | 
2
3
.
.
.

我正在使用它来编码,但它无法按我的预期打印出来。

use strict;
use warnings;

my $file = 'myfile.txt';
open my $info, $file or die "Could not open $file: $!";

while( my $line = <$info>)  {   

    if ($line =~ /info | info | info | /) {
        print $line;    
        last if $. == 10;
    }
}
close $info;

代码中是否有遗漏或出错的地方?

预期的结果应该在 CMD 上打印出来

info | info | info |
-------------------------
1    |  1   | 
2
3
.
.
.

【问题讨论】:

  • 竖线(|)是正则表达式中的特殊字符
  • 您希望它打印什么?
  • @harmic 我希望它能打印出“我的信息到.”的部分。它是一个文本文件
  • if ($line =~ /\Qinfo | info | info |/ .. 10) => perldoc.perl.org/perlop.html#Range-Operators
  • 请向我们展示预期的输出。

标签: perl


【解决方案1】:

在 Perl 中执行此操作的惯用方法是使用 the range operator,通常称为触发器:

perl -ne'print if /^info/ .. eof' yourfile.txt

在程序文件中是:

use strict;
use warnings;

while (<>) {
    print if /^info/ .. eof;
}

【讨论】:

  • eof 的一个好处是可以使用多个文件。
  • $. 绝不应该是0,尽管eof 的意图更明确。
【解决方案2】:

怎么样:

use strict;
use warnings;

my $file = 'myfile.txt';
open my $info, $file or die "Could not open $file: $!";
my $print = 0;
while( my $line = <$info>)  {   
    $print = 1 if $line =~ /^info/;
    print $line if $print;
    last if $. == 10;
}
close $info;

根据评论更新:

如果你想匹配info: ** info,你必须转义元字符(这里是* 字符):

$print = 1 if $line =~ /^info: \*\* info/;

如果有可选空格:

$print = 1 if $line =~ /^\s*info:\s*\*\*\s*info/;

【讨论】:

  • @user1204868:info 之前可能有一些空格字符?将正则表达式更改为:/^\s*info/.
  • 我可以和你核对一下,如果我需要查看信息的行中有 * 和 : 怎么办?例如,我正在尝试这样做 /^info: ** info/,有没有办法包含 * 和:?
【解决方案3】:

请试试这个。

while(<DATA>) { print $_, unless($_!~m/^$/ && $_!~m/My info/i && $. >= '10'); }

__DATA__
My info
info | info | info |
-------------------------
1    |  1   | 
2
3
.
.
.

【讨论】:

  • 谢谢!但是我的文本文件中的信息不是固定文本。行“1”可以变成4 | 2 |等等
  • 我知道你想如何逐行打印文本或模式匹配吗?由于我对代码说要打印每一行(包含值)应该打印为输出。谢谢。
  • 进一步了解您将打印与您的输入相对应的输出
  • 模式匹配。因为 ---- 之后的行不会被修复。
猜你喜欢
  • 1970-01-01
  • 2013-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
  • 2011-11-02
  • 2019-07-27
相关资源
最近更新 更多