chimiXchanga has asked for the wisdom of the Perl Monks concerning the following question:

Hello everyone, I'm stuck on the following and some help would be great! Thank you! So, I'm parsing a txt, here's some sample data:
PERMIT NO: 12-1833 VALUATION: $20,42 +5.00 PARCEL NO: ISSUED DATE: 25 +-Jun-12 LOCATION: 1416 SALMON RIVER RD OWNER: 1416 SALMON RIVER RD CONTRACTOR: HASCO HTG A/C SER +VICE CO INC RIVERSIDE, CA 3015 DURAHART ST RIVERSIDE, CA 951 276-3253 951 682-33366
and here's the code, parsing the line as 2 columns:
if ($column_line !~ /:/) { $column_line = trim($column_line); $data{$permit_no}{$key} .= $column_line; next; }
On the last 2 labels, how do I concat the last lines to the proper key? because using this I know it will concat only to my last $key, in this case being Contractor.

Replies are listed 'Best First'.
Re: Line concat to proper hash key
by poj (Abbot) on Mar 13, 2017 at 13:06 UTC

    Build a profile of the line and then use substr to extract the relevant data fields.

    #!perl use strict; use Data::Dump 'pp'; my @fields = ( 'PERMIT NO', 'VALUATION', 'PARCEL NO', 'ISSUED DATE', 'LOCATION', 'OWNER','CONTRACTOR'); my $match = join '|',map{ quotemeta }@fields; my $re = qr/$match/; #print $re."\n"; # %posn is fieldname => [startposn,length] my %posn = (); # fields on one line my @cols = (); my $rec = {}; # one record my %data = (); # many records while (<DATA>){ # start new record if (/PERMIT NO/){ add_record($rec); $rec = {}; } # build profile if (/:/){ @cols = (); while (/($re):/g){ push @cols,$1; $posn{$1}[0] = pos(); $posn{$1}[1] = 0; # to end of line # calc previous col length if (@cols>1){ my $prev = $cols[-2]; $posn{$prev}[1] = pos()-length($1)-$posn{$prev}[0]-1; } } } # extract data for my $c (@cols){ my $posn = $posn{$c}[0]; my $len = $posn{$c}[1]; my $str = ($len) ? substr $_,$posn,$len : substr $_,$posn; $str =~ s/^\s+|\s+$//g; #print "$c = '$str' $posn $len\n"; $rec->{$c} .= ' ' if exists $rec->{$c} && $str; $rec->{$c} .= $str; } } # last record add_record($rec); pp \%data; # add record to %data sub add_record { my $rec = shift; my $no = $rec->{'PERMIT NO'}; $data{$no} = $rec if ($no); }; # debug #pp \%posn; __DATA__

    Update ; removed length for last field

    poj
Re: Line concat to proper hash key
by huck (Prior) on Mar 13, 2017 at 08:48 UTC

    you didnt show us, but somehow you are parsing into the 2 cols before this point, so somehow $column_line comes from column 1 or col 2. You somehow know what col you are in. lets say it is in $coln; so when if ($column_line =~ /:/) is true you save 2 keys $keys{1} and $keys{2} from the parts before the : via $keys{$coln}=$key; then the line becomes $data{$permit_no}{$keys{$coln}} .= $column_line;

Re: Line concat to proper hash key
by Anonymous Monk on Mar 13, 2017 at 07:46 UTC
    Well you set $key to the proper value