Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Print text on the same line after match

by haukex (Archbishop)
on Dec 14, 2018 at 21:00 UTC ( [id://1227269]=note: print w/replies, xml ) Need Help??


in reply to Print text on the same line after match

I have only been able to come up with the match regex, but I'm not sure how to get the text at the end.

Unless you're really concerned about performance, it doesn't hurt to split things up into two regexes to make things easier to think about, for example you could say:

($number) = /(\d+)~$/ if /INC\*XX\*/;

But in this case it's not too difficult to do it in a single regex, see below.

(Update: To answer your question more basically, have a look at perlretut, where capturing groups are explained.)

Inside my perl script I assume that I will use something like this

It's almost never necessary to call perl from inside a Perl script. The while loop in the following code is the equivalent of a one-liner. I've added some checks to make sure that the number is found exactly once in the input file - I use defined instead of a boolean check to differentiate between 0, which Perl would consider false, and undef, which in this case means that no number was found. In the regex, I'm using a couple of techniques: /x for readability, and a negative lookbehind (?<!\d) to make sure the thing before the number is not also a number - not really required in this case (it's a bit of paranoia), but it could become an important technique if your match happens to get more complex. You didn't say whether there could be any characters in the string between "INC*XX*" and the number; if not, then the regex could be simplified to just /INC\*XX\*(\d+)~$/.

use warnings; use strict; use Data::Dumper; $Data::Dumper::Useqq=1; my $filename = 'cr835.txt'; open my $fh, '<', $filename or die "$filename: $!"; my $number; while (<$fh>) { if ( m{ INC\*XX\* .* (?<!\d) (\d+) ~ $ }x ) { die "number matched twice" if defined $number; $number = $1; } } die "no number found" unless defined $number; close $fh; print Dumper($number);

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1227269]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2024-04-19 12:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found