vinoth.ree has asked for the wisdom of the Perl Monks concerning the following question:
I have got an array with person details, from that array I need to get set of fields and values, some of the person may not have all the fields.
As there are no delimiter between each person, I tried below code like, first converted the array as single string and did regular expression matching.
As I am searching in a string, if a field is missing for a person its matching with next person value.
Example: if u run the above code you will get the below output
$VAR1 = { 'country' => '', 'name' => 'riya', 'address' => '', 'call' => '12345678', 'company' => '', 'age' => '34' }; $VAR1 = { 'country' => '', 'name' => 'vinoth', 'address' => '', 'call' => '12345678', 'company' => '', 'age' => '25' };
Here the riya user has no call field, but it taking the vinoth's call value, as per the regex its the expected behavior. how to avoid this behavior? I hope little change in the regex could resolve my issue.
use strict; use warnings; use Data::Dumper; my @fields=('age','company','call','address','country'); my @emp=('riya','vinoth'); my @array=( 'name riya', 'age 34', 'company xxxx', 'name vinoth', 'age 25', 'call 12345678', 'company xxxx', 'address asdd', 'country Ind'); my $details = join(',',@array); print "$details\n"; foreach my $name (@emp) { my %hash=(); $hash{'name'}=$name; foreach my $field (@fields){ if ($field eq 'name'){ if ($details =~/name\s*$name.*?,$field\s*(\S+),/g) { $hash{$field}=$1; } else{ $hash{$field}=''; } } elsif($field eq 'age'){ if ($details =~/name\s*$name.*?,$field\s*(\d+),/g) { $hash{$field}=$1; } else{ $hash{$field}=''; } } elsif($field eq 'company'){ if ($details =~/name\s*$name.*?,$field\s*(\S+),/g) { $hash{$field}=$1; } else{ $hash{$field}=''; } } elsif($field eq 'call'){ if ($details =~/name\s*$name.*?,$field\s*(\d+),/g) { $hash{$field}=$1; } else{ $hash{$field}=''; } } elsif($field eq 'country'){ print "$field\n"; if ($details =~/name\s*$name.*?,$field\s*(\S+),/g) { $hash{$field}=$1; } else{ $hash{$field}=''; } } elsif($field eq 'address'){ print "$field\n"; if ($details =~/name\s*$name.*?,$field\s*(\S+),/g) { $hash{$field}=$1; } else{ $hash{$field}=''; } } } print Dumper \%hash; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regex to capture field values
by choroba (Cardinal) on Jan 13, 2016 at 12:53 UTC | |
|
Re: Regex to capture field values
by GotToBTru (Prior) on Jan 13, 2016 at 13:37 UTC | |
by vinoth.ree (Monsignor) on Jan 14, 2016 at 13:13 UTC | |
|
Re: Regex to capture field values
by Anonymous Monk on Jan 13, 2016 at 13:32 UTC |