简体   繁体   中英

Perl Regex not finding pattern within script

I'm reading the contents of a log file, performing a regex on the lines and putting the results in an array, but for some reason there is no output.

use strict;
use warnings;

my $LOGFILE = "log.file";
my $OUTFILE = "out.file";

open(LOG, "$LOGFILE") or die ("Could not open $LOGFILE: $!\n");
open(TMP, ">", "$OUTFILE") or die ("Could not open $OUTFILE: $!\n");

my @data = (<LOG> =~ /<messageBody>(.*?)<\/messageBody>/sg);

print TMP "This is a test line. \n";

foreach (@data){
   print "@data\n";
   print "\n=======================\n";
}

close TMP;
close LOG;

My output is a file (out.file) and the only content is "This is a test line." I know the regex works because I tried it at the prompt with: -lne 'BEGIN{undef $/} while (/(.*?)</messageBody>/sg) {print $1} log.file > test.file

What am I doing wrong?

If you want to print the data's items, then you should do something like this:

foreach $item (@data){
   print TMP "$item\n";
   print TMP "\n=======================\n";
}

$item will loop through all array items and will be written in TMP file

Your data likely spans lines.

You'll therefore need to slurp the entire thing before using your regex:

my $logdata = do {local $/; <LOG>};

my @data = $logdata =~ m{<messageBody>(.*?)</messageBody>}sg;

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