Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

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
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]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (13)
As of 2015-04-01 09:37 GMT
Find Nodes?
    Voting Booth?

    Who makes your decisions?

    Results (2 votes), past polls