Update Oops. I didn't see the "preserve order" bit. In that case, this won't do exactly what you want. Sorry. See the other (better) solutions...
This should do what you want...
use strict;
my %data = ();
while (<DATA>) {
chomp;
my ($col1, $col2) = split /\s+/;
$data{$col1} .= "$col2 ";
}
print "$_: $data{$_}\n" foreach (sort keys %data);
__DATA__
text1 text-a
text2 text-b
text3 text-c
text1 text-d
text3 text-e
text3 text-f
Here's the explanation:
- The while loop goes through each line of input. In this case, each line in <DATA>.
- The line is then split on any whitespace into the two columns.
- To ensure uniqueness, the first column is used as the key name in a hash and the second column is appended to that.
- Then it prints each key, and its value using a foreach statement. The keys are also sorted.