Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: Assistance please

by grondilu (Friar)
on Nov 21, 2012 at 21:46 UTC ( #1005017=note: print w/replies, xml ) Need Help??

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1005017]
[stevieb]: Torturing one of my dev RPis to turn four 5v stepper motors at the same time (via Parallel:: ForkManager for 50k degrees (a whole lot of full turns!). Let's see if it burns out or not.
[stevieb]: My GPIO expander chips should arrive tomorrow, but I think I'll throw a shift register against them and see if all six I have will turn at once. Amps are near the breaking point, but I want to know max sustainable V and I output.

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2018-03-22 22:16 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (286 votes). Check out past polls.