views:

109

answers:

3

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__
+1  A: 
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.

Dave Hinton
i have updated my code but it still doesn't seem to work. It is still going to else statement.
A: 

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

akf
+2  A: 

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
Sinan Ünür