in reply to
Assistance please
Here is how I'd do it (I skip the part when you parse the weight table and prompt the user):
#!/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) {
/(?<element>[A-Za-z])(?<amount>\d+)?/;
$mass += ($+{amount} // 1) * $weights{$+{element}};
}
return $mass;
}
say mol_form "H2O";
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.