creating a hash with regex matches in perl

perl

Solution

$a{$1}++ for ($_=~/(\d+)/g);

This should be

$a{$_}++ for ($_=~/(\d+)/g);

and can be simplified to

$a{$_}++ for /\d+/g;

The reason for this is that `/\d+/g` creates a list of matches, which is then iterated over by `for`. The current element is in `$_`. I imagine `$1` would contain whatever was left in there by the last match, but it's definitely not what you want to use in this case.

Problem

Lets say i have a file like below: And i want to store all the decimal numbers in a hash. ``` hello world 10 20 world 10 10 10 10 hello 20 hello 30 20 10 world 10 ``` i was looking at this and this worked fine: ``` > perl -lne 'push @a,/\d+/g;END{print "@a"}' temp 10 20 10 10 10 10 20 30 20 10 10 ``` Then what i need was to count number of occurrences of each regex. for this i think it would be better to store all the matches in a hash and assign an incrementing value for each and every key. so i tried : ``` perl -lne '$a{$1}++ for ($_=~/(\d+)/g);END{foreach(keys %a){print "$_.$a{$_}"}}' temp ``` which gives me an output of: ``` > perl -lne '$a{$1}++ for ($_=~/(\d+)/g);END{foreach(keys %a){print "$_.$a{$_}"}}' temp 10.4 20.7 ``` Can anybody correct me whereever i was wrong? the output i expect is: ``` 10.7 20.3 30.1 ``` although i can do this in awk,i would like to do it only in perl Also order of the output is not a concern for me.

Original source