简体   繁体   English

Perl逐行读取和打印

[英]Perl read and print Line by line

I am trying to get a line by line print out for the following: 我正在尝试逐行打印以下内容:

My info


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

I am using this to code but it is unable to print out as what I expect. 我正在使用它进行编码,但无法按预期打印。

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;

Is there something missing or going wrong in the code? 代码中是否缺少或出错了?

The expected result should print out on CMD 预期结果应在CMD上打印

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

The idiomatic way to do this in Perl would be to use the range operator , commonly known as a flip-flop: 在Perl中这样做的惯用方式是使用范围运算符 ,通常称为触发器:

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

In a program file it would be: 在程序文件中,它将是:

use strict;
use warnings;

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

How about: 怎么样:

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;

Update according to comment: 根据评论更新:

If you want to match info: ** info , you have to escape metacharacters (here the * character): 如果要匹配info: ** info ,则必须转义元字符(此处为*字符):

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

and, if have optional spaces: 并且,如果有可选空格:

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

Please try this. 请尝试这个。

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

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

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

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