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.
But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.