Data Types in Perl

Perl has three principal data types: scalars, arrays, and hashes. You will certainly need to learn how to use scalars, and you should learn how to use arrays. For most WebWork questions you write, you probably won't need hashes.

  1. Scalars are any string or number. Named scalars start with $.
    $name = "Thomas Jefferson"; 
    $value = -5;
    
  2. Arrays of scalars. Named arrays start with @. Indexing for arrays always starts with zero.
    @ordinals = ("First","Second","Third"); 
    @values = (11,12,13);
    
    For arrays of consecutive numbers or letters, you can use the shortcuts below. Another useful shortcut is the qw( ) function, which converts a space-separated list into an array.
    @values = (11..13);
    @alphabet = (a..z);
    @names = qw(Mike Arnie Davide);
    
  3. Hashes are associative arrays of scalars. Named hashes start with %. An entry in a hash looks like key => value and associates a value to each key with notation very similar to function notation.
    %rankings = ( 
      First  => "Twins", 
      Second => "Yankees" 
    );
    %integers = ( One => 1, Two => 2 );
    
Scalars, arrays, and hashes can also be references to something. References are a bit more advanced and we discuss them later.

Accessing Scalars and Using Array Indices

To access a scalar inside an array or a hash, use

$ordinals[0]
$ordinals[-1]
$rankings{Second}
to get the values First, Third, and Yankees. These all start with $ because we're accessing a scalar. Notice that the indexing for the array starts with zero, and the last element in the ordinals array can be accessed either with the index 2 or -1. You can get the index for the last element in an array and the total number of elements in an array using
$#ordinals
scalar(@ordinals)
which return 2 (since the indexing starts with zero) and 3. You can create a new scalar whose value is an entry in an array or hash using
$age = $values[1];
$myteam = $rankings{First};
which will set $age = 12; and $myteam = "Twins";

Printing an Array

If you print an array such as @names you will get 3, which is not what you expected. If you use join(", ", @names); instead, then subsequent elements will be joined by a comma followed by a space and you will get Mike, Arnie, Davide, which is what you want.

Online References