in reply to Array problems.

You are testing the return value of the assignement. Instead you have to use ==
###WRONG if ($chemical = $periodicTable[$i][1]) { #always activates ###RIGHT if ($chemical == $periodicTable[$i][1]) {


In any case thanks for the element table in the array!

In your situation i normally use hashes:
my %periodic_table = ( 1 => {symbol=>'H', name => 'Hydrogen', weight = +> 1}, 2 => {symbol=>'He', name => 'Helium', weight => + 4}, )


HtH
L*
There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Replies are listed 'Best First'.
Re^2: Array problems.
by Laurent_R (Canon) on Oct 28, 2014 at 22:16 UTC
    In your situation i normally use hashes:
    my %periodic_table = ( 1 => {symbol=>'H', name => 'Hydrogen', weight = +> 1}, 2 => {symbol=>'He', name => 'Helium', weight => 4}, )
    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.

    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:

    <c> my %periodic_table = ( H => {atom_num => 1, name => 'Hydrogen', weight => 1}, He => {atom_num => 2, name => 'Helium', weight => 4}, # ... );
    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:
    my ($atom_nr, $elmnt_name, $atom_weight) = @{$periodic_table{$chem_sym +bol}}{qw /atom_num name weight/};
    Or, if the hash slice notation is intimidating to you, this more basic syntax:
    my $atom_nr = $periodic_table{$chem_symbol}{atom_num}; my $name = $periodic_table{$chem_symbol}{name}; my $atom_weight = = $periodic_table{$chem_symbol}{weight};