2

下面是两个字符串-

12/31/2011 05:34:27;U;11.comp;host=win workgroup=home username=bob cmemory=1325133456 qmemory=1325133456 smemory=1325133456 uptime=1325289867 
12/31/2011 01:09:20;D;12.comp;host=win workgroup=home username=sam cmemory=1325151687 qmemory=1325151687 smemory=1325151687 uptime=1325228636  session=4677 downtime=1325270175 Exit_status=0

从上面的字符串中,我想在 Perl 中使用 Regex选择hostworkgroup、和值。usernameuptimedowntime

下面是我的 Perl 脚本-

foreach $line (<FILE>) {
    if($line =~ m<\d{2}/\d{2}/\d{4}\s+\d{2}:\d{2}:\d{2};[U|D].*host=(\w+)\s+workgroup=(\w+)\s+hostname=(\w+)\s+.*uptime=(\d+)\s+.*(downtime=)?(\d*)>){
        my $host      = $1;
        my $workgroup = $2;
        my $hostname  = $3;
        my $uptime    = $4;
        my $downtime  = $5;
        print "host=$host workgroup=$workgroup hostname=$hostname uptime=$uptime downtime=$downtime\n";
    }
}

我在这里面临的唯一问题是因为downtime. 该属性可能不存在于该行中。我无法正确选择该字段。

4

1 回答 1

10

为什么不split改用?然后您可以将各种类别添加到哈希中,如下所示:

use strict;
use warnings;
use Data::Dumper;

while (<DATA>) {
    my ($date, $foo, $bar, $data) = split /;/, $_, 4;
    my %data = map { split /=/ } split ' ', $data;
    print Dumper \%data;
}

__DATA__
12/31/2011 05:34:27;U;11.comp;host=win workgroup=home username=bob cmemory=1325133456 qmemory=1325133456 smemory=1325133456 uptime=1325289867 
12/31/2011 01:09:20;D;12.comp;host=win workgroup=home username=sam cmemory=1325151687 qmemory=1325151687 smemory=1325151687 uptime=1325228636  session=4677 downtime=1325270175 Exit_status=0

输出:

$VAR1 = {
          'workgroup' => 'home',
          'cmemory' => '1325133456',
          'qmemory' => '1325133456',
          'uptime' => '1325289867',
          'smemory' => '1325133456',
          'username' => 'bob',
          'host' => 'win'
        };
$VAR1 = {
          'qmemory' => '1325151687',
          'Exit_status' => '0',
          'smemory' => '1325151687',
          'username' => 'sam',
          'host' => 'win',
          'workgroup' => 'home',
          'cmemory' => '1325151687',
          'session' => '4677',
          'downtime' => '1325270175',
          'uptime' => '1325228636'
        };

如果您现在想引用“停机时间”值,您可以执行以下操作:

my $downtime = $hash{downtime} // "N/A";

定义的或运算符在哪里//,在这里比逻辑或更受欢迎||

于 2013-03-12T17:20:24.790 回答