I am trying to do a program whereby the user inputs a chemical abbreviation, and gets the atomic weight back. I am learning and teaching myself perl. Any input apreciated. _________________________________________

I said "Can you give examples of the input you're expecting, the results you want and how you calculate the results" and you don't seem to have addressed that at all :)

Here's the kind of explaination that I expecting to see (trying to remember the chemistry I studied 25 years ago).

User inputs a chemical formula, e.g. H20.

This is split into elements and numbers, e.g. H, 2, 0. An element name is a capital letter followed by an optional lower case letter. An optional integer follows each element name. A missing integer is assumed to be 1.

A molecule's weight is then calculated by looking up the weights of the individual elements in the attached table, multiplying by the integer from the formula and summing all these weights.

For example in H20, the weight of oxygen (O) is 15.99 and the weight of hydrogen (H) is 1.01. The total weight is therefore 2 * 1.01 + 15.99 = 18.01.

Assuming all the records in the file are unique constants, and the file will only be updated when new elements are discovered, wouldn't it be better to place the data in memory along with your program? Then you wouldn't have to open/lock/read/search/close the file from disk. You can just jump straight to it using the user input.

This uses the "splice" function to pull elements from @parts two at a time. You can read the docs for splice by typing "perldoc -f splice" at your command line.

In Reply To

Code

next unless $chem{$elem};

$elem contains the next chemical element from the formula. %chem contains a table of elements togther with their atomic weight. If $elem isn't found as a key in %chem then it's not a real chemical element and we ignore it. We use "next" to skip to the next iteration of the innermost loop.

In Reply To

Code

$num ||= 1;

If the chemical symbol didn't have an integer after it then we need to treat it as 1. If the integer is missing then $num will contain the special value "undef" which evaluates as false. This code basically says that if $num doesn't contain a value(*) then set it to 1.

(*) To be picky, it actually says, if $num doesn't contain a _true_ value - so if $num contains a zero, it will also be set to 1. But I think that's probably the correct behaviour in this case.