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 . . . } #### #!/usr/bin/env perl use 5.018; use JSON::XS qw( encode_json ); my $current_line = q{}; while ( defined( my $line = ) ) { 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","data5","data6"] keyword 'keyword1' has 4 values: ["data1","data2","data3","data4"] keyword 'keyword3' has 1 values: ["data1"]