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

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

The file can be very large in size . It has a unique string inside it in the following format

Root identifier: <some number>

eg

Root identifier: 12987

I need to extract 12987in $rid.

How can I do this in Perl?

+3
source share
6 answers

Here is another way to do this 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
}
+4
source
while(<MR>) {
    chomp;
    ($rid) = $_ =~ m/Root identifier: (\d+)/;
    last if defined $rid;
}
+1
source

<> Perl , . unix- , man perlre Perl.

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

$rid

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

":" , \s* , .

0
source

I would 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);

PS: You can also use:

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

Source: https://habr.com/ru/post/1761764/


All Articles