Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Appending values to existing hash key

by graff (Chancellor)
on Mar 21, 2014 at 03:52 UTC ( #1079170=note: print w/replies, xml ) Need Help??

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!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1079170]
[Happy-the-monk]: very expensive, but high salaries, too :)

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2017-11-19 12:26 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (280 votes). Check out past polls.