in reply to Appending values to existing hash key

my @val = split(" ",$val); my $v = join (":", @val);
Assuming that you've already made sure that $val contains only the fields that need to be delimited by colon instead of whitespace, you could just do this:
$val =~ s/\s+/:/g
As for the other snippet, you could use a hash of arrays instead of a hash of concatenated strings, then join the array elements for each hash key after the whole set has been loaded. Here are the relevant loops (with a few other changes):
my %hash; while (<DATA>) { s/\s+$//; # remove all trailing whitespace (not just newline) s/(\S+\s+\S+\s+)//; # remove (and capture) first two fields my $key = $1; s/\s+/:/g; # join remaining fields with ":" push @{$hash{$key}}, $_; } foreach my $k (sort keys %hash) { print $k.join( ', ', @{$hash{$k}} )."\n"; }
There's nothing wrong with the way you originally did it - it works, it's clear, it's not wasteful, and that's all good.

Replies are listed 'Best First'.
Re^2: Appending values to existing hash key
by jaypal (Beadle) on Mar 21, 2014 at 04:34 UTC

    Thank you so much for all the explanation on each code snippet. Appreciate your help!