avanta has asked for the wisdom of the Perl Monks concerning the following question:

Hi all

just like we do group by in SQL for removing duplicate keys, i need to read a file with content as shown below
2010-01-01_audio,4 2010-01-01_text,5 2010-01-01_audio,6 2010-01-01_video,7 2010-01-02_audio,8 2010-01-02_text,6 2010-01-02_video,66 2010-01-02_text,45
Now I need to have one record of 2010-01-01_audio with the value = 4+6. and so on.The record shud look like

2010-01-01_audio,10

So, in short my output shud look like
2010-01-01_audio,10 2010-01-01_text,5 2010-01-01_video,7 2010-01-02_audio,8 2010-01-02_text,51 2010-01-02_video,66
I heard that using hash u cn do it but im not familiar with hash, and if i use the conventional way of using reading the file and foreach record, match it and the write it. but it is not possible to get the expected result.

PS: I cannot provide you with sample code as even I am not able to apply the logic.

any help would be grateful

Thanks
AvantA

Replies are listed 'Best First'.
Re: Need help with using Hash
by moritz (Cardinal) on Feb 05, 2010 at 09:39 UTC
    If you don't know what a hash is (and how you use it), I recommend to read the section about hashes in perlintro. More details can be found in the perldata document.
Re: Need help with using Hash
by Utilitarian (Vicar) on Feb 05, 2010 at 10:51 UTC
    Do read perldoc perlintro in particular (for this case, read all of it and learn the language) the "Perl variable types" section which introduces the concept of hashes.

    Now to the meat of your question, what is it you need to do

    • open a file perldoc -f open
    • Read each line in the file perldoc perlintro "Conditional and looping constructs", there's also an example of this in the documentation on open
    • Split the line into identifier and value perldoc -f split
    • Add the retrieved number to your identifier's value in the hash, should be a doddle after reading the perlintro document.
    Welcome to the monastery and hope you enjoy the learning experience ;)

    print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."