Perl Regex for zero or one match
perl, regex
Solution
Why not use `split` instead? Then you could add the various categories to a hash, like so:
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
Output:
$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'
};
If you now want to refer to the "downtime" value, you can do something such as:
my $downtime = $hash{downtime} // "N/A";
Where `//` is the defined-or operator, somewhat preferred here over logical or `||`.
Problem
Below are the two strings- ``` 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 ``` From above strings I want to pick `host`, `workgroup`, `username`, `uptime` and `downtime` values using Regex in Perl. Below is my Perl script- ``` 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"; } } ``` The only problem, I am facing here is because of `downtime`. This attribute may not be present in the line. I am not able to pick this field properly.