in reply to Manually incrementing @ array during for
You need to get fancier in your parsing. You need to examine each line as it comes in, determine if it's a continuation (presuming leading whitespace indicates this, going from your example data) and (if not) append to the "current line". Once you're sure you have a full line, then process it and clear out the current line. Handwavy, vague outline:
my $current_line = q{}; while( defined( my $line = <> ) ) { chomp( $line ); if( $line =~ m{^ \s+ \w+ }x ) { $current_line .= $line; next; } else { _process_line( $current_line ); $current_line = $line; } } if( $current_line ) { _process_line( $current_line ); } sub _process_line { my( $line ) = $shift; ## do whatever . . . }
Update: Fuller example with sample data and fixing a bugglet first time through loop.
#!/usr/bin/env perl use 5.018; use JSON::XS qw( encode_json ); my $current_line = q{}; while ( defined( my $line = <DATA> ) ) { chomp($line); if ( $line =~ m{^ \s+ \w+ }x ) { $current_line .= $line; next; } else { if ($current_line) { _process_line($current_line); } $current_line = $line; } } if ($current_line) { _process_line($current_line); } sub _process_line { my ($line) = shift; my ( $kwd, @vals ) = split( /\s+/, $line ); say qq{keyword '$kwd' has }, scalar @vals, qq{ values: }, encode_json( \@vals ); } exit 0; __END__ keyword1 data1 data2 data3 keyword2 data1 data2 data3 data4 data5 data6 keyword1 data1 data2 data3 data4 keyword3 data1
~ $ perl $_ keyword 'keyword1' has 3 values: ["data1","data2","data3"] keyword 'keyword2' has 6 values: ["data1","data2","data3","data4","dat +a5","data6"] keyword 'keyword1' has 4 values: ["data1","data2","data3","data4"] keyword 'keyword3' has 1 values: ["data1"]
The cake is a lie.
The cake is a lie.
The cake is a lie.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Manually incrementing @ array during for
by cniggeler (Sexton) on Mar 16, 2020 at 16:40 UTC | |
by jcb (Parson) on Mar 17, 2020 at 01:34 UTC | |
by Aaronrp (Scribe) on Apr 11, 2020 at 20:45 UTC | |
by Fletch (Bishop) on Mar 16, 2020 at 18:33 UTC | |
by AnomalousMonk (Archbishop) on Mar 16, 2020 at 20:20 UTC |