<?xml version="1.0" encoding="windows-1252"?>
<node id="1005017" title="Re: Assistance please" created="2012-11-21 16:46:28" updated="2012-11-21 16:46:28">
<type id="11">
note</type>
<author id="946047">
grondilu</author>
<data>
<field name="doctext">
&lt;p&gt;Here is how I'd do it (I skip the part when you parse the weight table and prompt the user):&lt;/p&gt;

&lt;code&gt;
#!/usr/bin/perl
use strict;
use warnings;

# whatever you need to fill %weights
...

sub mol_form {
    my $formula = shift;
    my $mass;
    for ($formula =~ /[A-Za-z]\d*/g) {
        /(?&lt;element&gt;[A-Za-z])(?&lt;amount&gt;\d+)?/;
        $mass += ($+{amount} // 1) * $weights{$+{element}};
    }
    return $mass;
}

say mol_form "H2O";
&lt;/code&gt;

&lt;p&gt;The most tricky part is to separate each group of element+optionalquantity, and then to process them.  That's why I ended up with two regexes, not just one.&lt;/p&gt;</field>
<field name="root_node">
1004991</field>
<field name="parent_node">
1004991</field>
</data>
</node>
