简体   繁体   English

Perl正则表达式未在脚本中找到模式

[英]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." 我的输出是一个文件(out.file),唯一的内容是“这是测试行”。 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 我知道正则表达式有效,因为我在提示符下尝试了以下命令:-lne'BEGIN {undef $ /}而(/(.*?)</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 $item将遍历所有数组项并将被写入TMP文件

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM