On Jan 29, 2008 11:02 AM, Rob Dixon <[EMAIL PROTECTED]> 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;

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to