Creating a hash in perl with all the regex matches

Thursday, January 31, 2013 , 0 Comments

As i explained here :http://theunixshell.blogspot.com/2013/01/capturing-all-regex-matches-into-array.html about storing each and each regex match in an array,Now let's see how do we store each and every regex match in a hash instead.

Lets say we have text file like below:

hello world 10 20
world 10 10 10 10 hello 20
hello 30 20 10 world 10


I want to store each and every decimal integer here in a hash as a key and count of their occurances in a value for that key.

Below is the solution for that:

perl -lne '$a{$_}++for(/(\d+)/g);END{for(keys %a){print "$_.$a{$_}"}}' Your_file

output generated will be:

> perl -lne '$a{$_}++for(/(\d+)/g);END{for(keys %a){print "$_.$a{$_}"}}' temp
30.1
10.7
20.3






0 comments: