Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

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.


Comment on Re: Appending values to existing hash key
Select or Download Code
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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1079170]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (12)
As of 2015-07-29 21:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (269 votes), past polls