Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Regex to select multiple lines

by pernod (Chaplain)
on Dec 09, 2004 at 16:13 UTC ( #413611=note: print w/replies, xml ) Need Help??


in reply to Regex to select multiple lines

Ok, some heavy assumptions in the following code, but oh well. Here goes:

#! /usr/bin/perl use strict; # Assume a blank line to mean no whitespace $/ = "\n\n"; foreach my $record ( <DATA> ) { chomp( $record ); my @data = split( "\n", $record ); # Take the last element of the last three lines in the record my $txname = ( split( / /, $data[ -3 ] ) )[-1]; my $txtime = ( split( / /, $data[ -2 ] ) )[-1]; my $errorcode = ( split( / /, $data[ -1 ] ) )[-1]; print "$txname\t\t\t$txtime\t\t$errorcode\n"; } __DATA__ Message Type: Name: Someone Time: Now Errorcode: 42 Message Type: Seismic instability Source: Japan Name: Anyone Time: Yesterday Errorcode: 23 Message Type: Author: Lewis Carrol Work: The hunting of whatever Name: Bellman Time: 12:32:1892 Errorcode: Snark!

The main point here is the use of the Input Record Separator ($/) to split the file into records. Then you can split on newlines and fetch the last three rows. The code above contains quite a bit of room for improvement in the regex-department (grabbing results into $1 and friends, for example), but I'll not muddy my point about the $/.

On my box, this (untidily) prints:

Someone Now 42 Anyone Yesterday 23 Bellman 12:32:1892 Snark!

Good luck!

pernod
--
Mischief. Mayhem. Soap.

Replies are listed 'Best First'.
Re^2: Regex to select multiple lines
by beeny (Initiate) on Dec 09, 2004 at 17:02 UTC
    Okie after reviewing the replies to my question, thanks to all of you. I came up with this.
    sub chewitup { for($i=0; $i<$array_size; $i++){ chomp($data[$i]); if($data[$i] =~ /Message Type:/){ @details0=split / /, $data[$i]; unless($data[$i] eq $blank){ if($data[$i] =~ /Error Code:/){ @details2=split / /, $data[$i]; } if($data[$i] =~ /Transaction Time:/){ @details1=split / /, $data[$i]; } next $i; } $txname=$details0[2]; $txtime=$details1[2]; $errorcode=$details2[2]; print OUT "$txname\t\t\t$txtime\t\t$errorcode\n"; } } }

    Opinions please...thanks

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2019-08-24 07:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?