in reply to Regex to capture field values
If the purpose of @emp and @fields is to restrict the output to just those, then you can use them to filter.
#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my @emp = ('riya','vinoth'); my @fields = ('age','company','call','address','country','name'); my %nameh = map { $_, 1 } @emp; my %fieldh = map { $_, 1 } @fields; my @array = ( 'name riya', 'age 34', 'company xxxx', 'fax 8765432109', 'name vinoth', 'age 25', 'call 12345678', 'company xxxx', 'address asdd', 'country Ind', ); my %hash; my $name; while (@array) { my $line = shift @array; if (my ($field, $value) = $line =~ /^(.*) (.*)/) { $name = $value if 'name' eq $field; $hash{$name}{$field} = $value if ($nameh{$name} && $fieldh{$fi +eld}); } else { warn "Invalid line '$line'.\n"; } } print Dumper \%hash;
The output will omit the fax field I added to riya's data because it was not found in @fields.
Update: added name to list of fields! This is what comes of not testing your code.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Regex to capture field values
by vinoth.ree (Monsignor) on Jan 14, 2016 at 13:13 UTC |