Assignment and variables

Assignment in computer programming languages is an operation of storing a value somewhere in the computer's memory that is accessed by its name.

In Perl 5 there are three built-in data types: scalars, arrays and hashes (or associative arrays). Scalars can hold strings and numbers. Arrays are ordered lists of scalars where values are accessed by index. Hashes are unordered associative array where values are accessed by keys. Variables that hold scalars, arrays or hashes are prefixed with $, @ and % respectively.

Variables are usually declared by using my keyword. For example:

my $x = 1;
say $x;

Exercise

Assign to a variable y string 'Hello, world!' and print it.

my $
say

Scalars

Depending on what the variable holds (a number, a string) there are different operators your can use.

Let's say you want to sum two number values:

my $x = 1;
my $y = 2;

say $x + $y;

Or you want to concatenate two string values:

my $x = 'Hello';
my $y = 'There';

say $x . $y

If you will try to use + on strings or . on numbers they will be automatically converted to appropriate types.

my $x = 1;
my $y = '2 times';

say $x . $y;
say $x + $y;

As you can see in the second example the string '2 times' was converted to number, which is 2.

Exercise

Contatenate and print the string 'Result=' and the sum of 42 and 13.

my $x = ;
my $y = ;

say

Arrays

Arrays can hold a list of scalars.

my @array = (1, 2, 3);

say @array;

Basic array manipulations include getting an element by index (starting from 0), getting the last index, shifting and popping values.

my @array = (1, 2, 3);

# Get the third element
say $array[2];

# Get the last index
say $#array;

push @array, 4;
say @array;

pop @array;
say @array;

shift @array;
say @array;

unshift @array, 0;
say @array;

As you probably have noticed when accessing array element we changed @ to $, because the element of array is a scalar, and scalars are prepended with symbol $.

Exercise

Given the array that holds list (1, 2, 3, 4) print the third element.

my @array = ;
say

Hashes

Hash or associated arrays are unordered collections of scalars that can be accessed by a key. A key is usually a string.

my %hash = ('key1', 'value1', 'key2', 'value2');

Instead of using comma for separating keys and values Perl provides a more readable operator =>, for example:

my %hash = (key1 => 'value1', key2 => 'value2');

Basic hash manipulations

As with arrays when accesing hash key, the variable becames a scalar, we use symbol $ and braces {}:

my %hash = (key1 => 'value1', key2 => 'value2');

say $hash{key1};

Geting all hash keys and values

my %hash = (key1 => 'value1', key2 => 'value2');

say keys %hash;
say values %hash;