Lazer
Lazer

Reputation: 95000

How to read from a file and do a grep in Perl?

open(MR, "<path_to_report");
$rid;

The file might be very big in size. It has a unique line inside it in the following format

Root identifier: <some number>

for example

Root identifier: 12987

I need to extract 12987 to $rid.

How can I do that in Perl?

Upvotes: 3

Views: 5046

Answers (6)

Nikhil Jain
Nikhil Jain

Reputation: 8352

    #!/usr/bin/perl
    use strict;
    use warning;
    open(IN, '<', file) or die $!;
    read(IN, my $data, -s file);
    $rid =~ $data = m/Root identifier: (\d+)/;
    print"$rid";
    close(IN);

Upvotes: 0

Eric Strom
Eric Strom

Reputation: 40152

Here is another way to to do it using more modern idioms:

use warnings;
use strict;

open my $file, '<', 'path_to_report'   # 3 arg open is safer
     or die "could not open file: $!"; # checking for errors is good

my $rid;
while (<$file>) {
    last if defined( ($rid) = /Root identifier: (\d+)/ );
}

close $file;

if (defined $rid) {
    # do something with $rid
}

Upvotes: 4

Pedro Silva
Pedro Silva

Reputation: 4710

while(<MR>) {
    chomp;
    ($rid) = $_ =~ m/Root identifier: (\d+)/;
    last if defined $rid;
}

Upvotes: 1

polemon
polemon

Reputation: 4782

I'd use something like this:

#!/usr/bin/perl

use 5.010;

open(MR, "<", file) or die "cannot open file";
while(<MR>) {
    last if(/^Root identifier: (\d+)$/ig);
}

say($1);

P.S.: You could also use:

last if(/^Root identifier: (\d+)$/ig) while(<MR>);

Upvotes: -2

HerbN
HerbN

Reputation: 1509

The following will find the number and leave it in $rid

open(MR, "<path_to_report");
while(<MR>) {
   chomp;
   next unless /Root identifier:\s*[0-9]+\s*$/;
   tr/\D//g;
   $rid = $_;
}

You didn't specify exact amount or type of white space between the ':' and the number or after the number so I'm including \s* before and after the digits to allow for a variable amount.

Upvotes: 0

Dima
Dima

Reputation: 39429

Read one line at a time using the <> operator, and use Perl regular expressions to find and extract what you need. If you are in a unix-like environment check man perlre for Perl regular expressions reference.

Upvotes: 0

Related Questions