use strict; use warnings; open my $words, "<", "words.txt" or die "Cannot open words.txt: $!\n"; my $lasttype; my @text; while( <$words> ) { chomp; my @row = split /\t/; my $text = $row[0]; my $type = ( $row[-1] =~ /\w-(\w+)/ ) ? $1 : ""; $lasttype = $type unless @text; # special treatment for first row if( $type eq $lasttype ) { push @text, $text; } else { print ''."$lasttype@text\n" if $lasttype; $lasttype = $type; @text = ( $text ); } } # print what's left over when all input read print ''."$lasttype@text\n" if $lasttype; close $words;