简体   繁体   中英

Extracting numbers from a text file using perl

I have a text file which has data of the form ..

*****yz = 1.4333******

result= 3.58e-01


*******ayf = 25.00 ****yz = 1.34
result= 3.24e-01


I want to extract the values beside result & push it into an array.

Is there more code you didn't give in the example? Like output of the result array? Otherwise there are some things to consider:

  • leading space in regex: This will not match your example, since result there starts at the beginning of the line. In general, if you want to be more flexible with possibly occuring spaces, insert \\s* at the according places.
  • scientific number matching: If you expect numbers other than scientific notation with negative exponents to appear, you have to adopt your regex that way. There are plenty of example out there.

For your extended code:

  • please use use strict; and use warnings; in every script
  • use the 3-argument-mode of open and possibly lexical file handlers ( my $fh instead of FH ). The 3-argument-mode ensures you don't forget to specify the actual mode (read/write/etc.) in which to open the file, amongst other things.
  • close(FH) your file handlers before using them on other files

Not closing IN2 seems to be one problem in your code, for instance.

This might work:

open my $fh, '<', $filename or die;
my @array;
/result\s*=\s*(\S+)/i and push @array, 0+$1 while <$fh>;    # 0+$1 or just $1
close $fh;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM