Re: groups of values from an array



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



Relevant Pages

  • Re: Dr. John Harshmans embarrassing "literalism" claims
    ... I will push Atheist heavy weights Darwin and Dawkins around in my ... by the large number of Christians who accept it. ...
    (talk.origins)
  • Re: Dashboard, Malware and a Theory.. Vindicated!
    ... download and install with no warnings at all ... I've sometimes suggested that Macs have less malware because ... That's the problem with warnings; ...
    (comp.sys.mac.advocacy)
  • Re: BARRY & THE BROTHERS TO THE RESCUE SHOOTDOWN
    ... The warnings before and during the ... > cowboys want to be play chicken with MIG's in or even around Cuban ... And don't forget that transcript from the Miami tower. ...
    (soc.culture.cuba)
  • Re: function system() from stdlib.h
    ... warnings, so long as those warnings are not required by the standard. ... switch ... I suppose the compiler decides not to warn when there is a comment before the following case, because an experienced programmer using this behavior of switch/case generally puts a comment there, just to inform that the absence of the break statement is intentional. ...
    (comp.lang.c)
  • Re: 06 ISF Roll Call
    ... a tumbling bike, push it off, and yell at me, "Did you get a picture? ... I was riding with Just A Girl and she broke her friggin' ...
    (rec.motorcycles.dirt)