开发者

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

开发者 https://www.devze.com 2023-01-13 00:36 出处:网络
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
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: 1开发者_运维知识库2987

I need to extract 12987 to $rid.

How can I do that in Perl?


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
}


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


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.


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.


    #!/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);


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>);
0

精彩评论

暂无评论...
验证码 换一张
取 消