new_bird
new_bird

Reputation:

How to read information from file using regex and print it?

I am working with the following data:

__DATA__
Branch 1: 10..11

      13 E 0.496 -> Q 0.724
      18 S 0.507 -> R 0.513
      19 N 0.485 -> S 0.681

Branch 2: 11..12

      81 R 0.891 -> Q 0.639
      88 Y 0.987 -> S 0.836

From the above data, I want to read numbers present before a character and then print them out. So for instance in Branch 1 I want to read 13 , 18, 19 and from Branch 2, I want to read 81 88.

I have written the following code for reading Branch 1 but it doesn't seem to work. Any suggestions?

#!/usr/bin/perl
use strict;
use warnings;

my $find = 'Branch 1:';
$a = '0';

open (FILE, "/user/Desktop/file") || die "can't open file \n";
while (my $body = <FILE>) {
    if ($body =~ m/$find/) {
        my $value = my $body=~ m/\d{2}\s[A-Z]/;
        print "$value \n";
    }
    else {
        $a++; # only to check it reading anything
        print "$a \n";
    }
}
__END__

Upvotes: 1

Views: 342

Answers (3)

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118118

The following seems to do what you want:

#!/usr/bin/perl

use strict;
use warnings;

while ( <DATA> ) {
    if ( /^(Branch [0-9]+): / or /^\s+([0-9]+) [A-Z]/ ) {
        print "$1\n";
    }
}

__DATA__
Branch 1: 10..11

      13 E 0.496 -> Q 0.724
      18 S 0.507 -> R 0.513
      19 N 0.485 -> S 0.681

Branch 2: 11..12

      81 R 0.891 -> Q 0.639
      88 Y 0.987 -> S 0.836

Upvotes: 3

akf
akf

Reputation: 39475

one thing is that you do not have a space between your [A-Z] and the 0

Upvotes: 0

dave4420
dave4420

Reputation: 47042

m/\d{2}\s[A-Z]0/

should be

m/\d{2}\s[A-Z]/

or possibly

m/\d{2}\s[A-Z]\s0/

or even

m/\d{2}\s[A-Z]\s\d/

The point being that your code is expecting a 0 immediately after the letter, but there is a space inbetween.

Upvotes: 2

Related Questions