1

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

0

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

won't that match the first float 6010.822? I think there should be and end-of-sting anchor: m/(\d+\.\d+)$/...also for correctness you should escape the '.' operator
@Davs Yes, I just corrected the first thing I saw was wrong. I have now fixed everything.
Thanks TLP and Dave. And thanks all who gave their thoughts to this. Solution (by TLP) works good. Appreciate this forum.
@user3182647 You're welcome. If your question has been answered, you can mark an answer as accepted by clicking the checkmark.
0

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!

2 Comments

Thanks TLP and Dave. And thanks all who gave their thoughts to this. Solution (by TLP) works good. Appreciate this forum.
@user3182647 - Please consider checking "Accept" by TLP's answer if it's working for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.