Re: groups of values from an array
- From: chas.owens@xxxxxxxxx (Chas. Owens)
- Date: Tue, 29 Jan 2008 11:25:30 -0500
On Jan 29, 2008 11:02 AM, Rob Dixon <rob.dixon@xxxxxxx> wrote:
snip
if (/^==/) {snip
elsif (/(.+):\s+(.+)/) {
Just a few minor quibbles. It is safer to say /^={80}$/ (we don't know
if == is valid in the field names), you need to limit the greediness
of the first capture (there might be a : followed by a space in the
value), you need to be able to match nothing for the field (empty
values should still show up in the hash), you need to warn the user of
malformed records, and you need to handle the case where the file does
not end with the separator.
use strict;
use warnings;
my @data;
my %record;
while (<DATA>) {
chomp;
if (/^={80}$/) {
next if keys(%record) == 0; #skip empty records
push @data, {%record} if %record;
%record = ();
} elsif (my ($k, $v) = /(.+?):\s+(.*)/) {
$record{$k} = $v;
} else {
warn "improper record format on line $.\n";
}
}
if (keys %record) {
push @data, {%record};
%record = ();
}
Of course, I would prefer to read the whole record in and manipulate
it at once (as I did in my example). Of course, the usage of map
makes it harder to add the warning, so you might consider doing this
instead:
#my %record = map { /(.*?):\s+(.*)/ } split /\n/, $rec;
my %record;
for my $line (split /\n/, $rec) {
my ($k, $v) = $rec =~ /(.+?):\s+(.*)/;
if (defined $k) {
$record{$k} = $v
} else {
warn "improper record format on line $.\n";
}
}
push @record, \%record;
.
- References:
- groups of values from an array
- From: Peter Horvath
- Re: groups of values from an array
- From: Rob Dixon
- groups of values from an array
- Prev by Date: Reference and assignment question
- Next by Date: Re: Clear a hash
- Previous by thread: Re: groups of values from an array
- Next by thread: Reference and assignment question
- Index(es):
Relevant Pages
|