http://www.perlmonks.org?node_id=1152667

vinoth.ree has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

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; }

All is well. I learn by answering your questions...