Prasad tonds
Prasad tonds

Reputation: 13

perl extract/match last floating point number from string

Need to extract last floating point number from the string below and save into a variable.

F791775                (6010.822, 4396.812) (6013.341, 4405.921)   9.451  

Expected output: 9.451

Used the following regex

my $inj_spacing = $line =~ m {(\d+.\d+)}x;

but this extracts= 1

Upvotes: 1

Views: 3263

Answers (2)

TLP
TLP

Reputation: 67900

You get the number 1 as a result because your regex is in scalar context (because the left-hand side argument is a scalar). It is merely a true value, denoting that the regex matched.

What you want is to impose a list context, which can be done by adding parentheses:

my ($inj_spacing) = $line =~ m {(\d+\.\d+)}x;

(You also need to escape the period, as tools said)

Also, of course, this will match the first possible time, so you need to anchor it to the end:

my ($inj_spacing) = $line =~ m {(\d+\.\d+)\s*$}x;

I added \s* to account for optional whitespace. This is not recommended if trailing whitespace indicates missing data in the last column (e.g. with csv data). But for an informal type of text matching, it will prevent false mismatches.

Upvotes: 7

Kenosis
Kenosis

Reputation: 6204

If your string always has that format, another option is to use split to get the last fp number:

use strict;
use warnings;

my $str = 'F791775                (6010.822, 4396.812) (6013.341, 4405.921)   9.451';
my $inj_spacing = ( split ' ', $str )[-1];
print $inj_spacing;

Output:

9.451

Hope this helps!

Upvotes: 0

Related Questions