I have a hash
something like :
abc=>1
hello=>32
abc=>4
hello=>23
hello=>12
xyz=>18
how can we concatenate the values, whose keys are same.
So the output will be:
abc=>"1,4"
hello=>"23,12,32"
xyz=>"18".
I tried by sorting the hash by keys then checking for each key, if they are same then concatenate the value, but i am not getting that how to compare two keys in same loop.
Thanks in advance.
If it's a list with key value pairs you are talking about then you could do something like:
Since it is unclear what you are really trying to do, I am guessing that you have a file that you need to change. In which case, a one-liner might be in order.
Output:
Note that the keys in the output will not be in the same order as the input. You can sort the keys if you like, but I opted not to.
Explanation:
-l
will remove line endings while reading, and put them back while printing-n
will place awhile(<>)
loop around the program, reading the file (or STDIN) line by line.//
is thedefined-or
operator. It will return the RHS if the LHS is undefined.}{
is the eskimo kiss operator which only works with the-n
option. What it does is basically the same as an END block, it performs the following code at the end of the input.The exact way this works depends on the real source of your data, but this program shows a way to read the information from the
DATA
filehandle to build and dump a hash.The values of the hash are anonymous arrays that contain all the values corresponding to the same key.
output