Simple Variables

Variables in Perl have a special leading character, which denotes whether it's a scalar, array or hash.

Scalars

$ denotes a SCALAR: simple variable. Example:

 my $name;
 $name = 'Jason';

Arrays

@ denotes an ARRAY, linear list of scalars. Example:

 my @names;

Elements are addressed using an index, [0] [1] [2] etc. Elements of an array are SCALARs:

 $names[0] = 'Jason';
 $names[1] = 'Peter';

Hashes

% denotes a HASH (MAP): 'array' that is indexed using keys. Example:

 my %address;

Elements of a hash are again scalars. NOTE that addressing in a hash is done using { and } (not square brackets, as with linear arrays):

 $address{'Jason'} = '20022 Main St.';
 $address{'Peter'} = '90210 Beverly Hills';

Exercise

Write a program that uses the above @names and %address variables, including their assignments (just copy the above lines into your program).

Next have the program print out the information as follows:

 Jason: 20022 Main St.
 Peter: 90201 Beverly Hills

Use the builtin function for displaying stuff, as in:

 print("Hello World\n");                # one string, \n is newline
 print("Hello", " ", "World\n");        # 3 arguments separated by comma

Add your code below this documentation, then run it using 'perl 01-vars.pl'. Or put your code in your own file 'myfile.pl' then run it using 'perl myfile.pl'.

What's my doing in 'my @names'

Variables are DECLARED using the keyword 'my', meaning that their lexical scope is limited to the current block (file, or {...block...}). Variables are ASSIGNED then without any keyword, since they are already known:

 my @names;             # declaration using my
 $names[0] = 'Jason';   # assignment

Variables can be declared and assigned at the same time, with the same statement. For example in the case of a scalar:

 my $amount = 123.45;

For an array, we use parentheses ( and ):

 my @names = ('Jason', 'Peter');

For a hash, we also use ( and ). The key can be anything such as a string and a number, and is separated by => from the value. Key/value pairs are separated by a comma from the next pair:

 my %address = ('Jason' => '20022 Main St.',
                'Peter' => '90201 Beverly Hills' );

Because strings as keys are so common, you can leave out the quotes around the key (but not around the value).

 my %address = (Jason => '20022 Main St.',
                Peter => '90201 Beverly Hills' );