in reply to Recursive capture of a variable number of elements using regexp
$_ = 'CH4N2O'; print $_,"\n"; %hash = /([A-Z][a-z]?)(\d*)/g; while ( ($key, $value) = each %hash) { $value ||= 1; print "\t$key\t$value\n"; }
Note I also changed your grouping a little.
Update:If your chemical formulas encode structural information (e.g. HOH for water), then keys in a hash will get clobbered. You can, of course, substitute an array for the hash, and compensate appropriately. Thanks jwkrahn for reminding me to include a warning.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Recursive capture of a variable number of elements using regexp
by jwkrahn (Abbot) on Apr 09, 2009 at 18:31 UTC | |
by linuxer (Curate) on Apr 09, 2009 at 18:47 UTC | |
by kennethk (Abbot) on Apr 09, 2009 at 19:23 UTC | |
|
Re^2: Recursive capture of a variable number of elements using regexp
by seaver (Pilgrim) on Apr 09, 2009 at 18:08 UTC |