in reply to Re: Array problems.
in thread Array problems.
In your situation i normally use hashes:While I would definitely agree that using a hash would often be better for such lookups, your example would work perfectly (and probably slightly faster) with an array (an array of hashes, that is), since you are using the atomic number as a key to your hash, and atomic numbers are just all the integers between 1 and 118, so that an array is a perfect fit.my %periodic_table = ( 1 => {symbol=>'H', name => 'Hydrogen', weight = +> 1}, 2 => {symbol=>'He', name => 'Helium', weight => 4}, )
Having said that, it seems that the original poster is accessing the data through the chemical symbol, rather that the atomic number, and for that, a hash is much much better and way faster.
To the OP: The structure of the hash would have to be something like this:
The advantage is that it is then easier (and faster) to retrieve the characteristics of an element. For example, instead of scanning the whole array to find an element, one could have direct access to the characteristics of an element using a hash slice:<c> my %periodic_table = ( H => {atom_num => 1, name => 'Hydrogen', weight => 1}, He => {atom_num => 2, name => 'Helium', weight => 4}, # ... );
Or, if the hash slice notation is intimidating to you, this more basic syntax:my ($atom_nr, $elmnt_name, $atom_weight) = @{$periodic_table{$chem_sym +bol}}{qw /atom_num name weight/};
my $atom_nr = $periodic_table{$chem_symbol}{atom_num}; my $name = $periodic_table{$chem_symbol}{name}; my $atom_weight = = $periodic_table{$chem_symbol}{weight};
|
|---|