#!/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) { /(?[A-Za-z])(?\d+)?/; $mass += ($+{amount} // 1) * $weights{$+{element}}; } return $mass; } say mol_form "H2O";