user1204868
user1204868

Reputation: 606

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

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

Upvotes: 1

Views: 225

Answers (3)

Toto
Toto

Reputation: 91373

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):

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

and, if have optional spaces:

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

Upvotes: 3

ssr1012
ssr1012

Reputation: 2589

Please try this.

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

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

Upvotes: 1

TLP
TLP

Reputation: 67900

The idiomatic way to do this in Perl would be to use the range operator, commonly known as a flip-flop:

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

In a program file it would be:

use strict;
use warnings;

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

Upvotes: 4

Related Questions