Broad Network


Lists in Perl

Perl Data Types – Part 4

Perl Course

Foreword: In this part of the series, I talk about lists in Perl.

By: Chrysanthus Date Published: 22 May 2015

Introduction

This is part 4 of my series, Perl Data Types. In this part of the series, I talk about lists in Perl. You should have read the previous parts of the series before reaching here, as this is a continuation. All data in Perl is a scalar, an array of scalars, or a hash of scalars. A scalar contains one single value in any of three different flavors: a number, a string, or a reference. A scalar variable is preceded by $. An array is a variable beginning with @ to which a list has been assigned. A hash is a variable beginning with % to which a special list has been assigned.

A List
In Perl, a list is a set of items separated by commas. The following is a list of items, which were found on a table.

    'pen', 'book', 'ruler', 'computer'

If a number is a member of the list, it does not have to be typed in quotes. Any string member has to be typed in quotes. If you want to consider the list as a group, place the list in parentheses, as follows:

    ('pen', 'book', 'ruler', 'computer')

The following is the creation of an array:

    @arr = ('pen', 'book', 'ruler', 'computer');

An array is not really a list, that is why, an array operated in scalar context returns but the length of the array.

With an assignment operator, if the left hand operand is a scalar, the value of the last item in the list will be returned. So, in the statement:

    $item = ('pen', 'book', 'ruler', 'computer');

the value of $item becomes 'computer'. Note: in this statement we do not have any array; we have but a list.

Subscripting a List
The subscript for an array element is an integer inside square brackets. The subscript for a hash element is text inside curly brackets.

You can subscript a list similar to the way you subscript an array. Try the following code:

use strict;

    my $item = ('pen', 'book', 'ruler', 'computer')[2];

    print  $item;

The output is, ruler. The list in this code is not an array. The square brackets with its subscript is just at the end of the list. The expression returns the value whose index is the subscript (index counting begins from zero).

Sublist in a List
A sublist in a list becomes interpolated such that each item in the sublist becomes an item in the main list. Try the following code:

use strict;

    my @arr = ('pen', 'book', ('aa', 15, 'cc'), 'ruler', 'computer');

    print $arr[3];

The output is, 15. A list is like a value; it has to be separated from the other items of the main list by commas: one comma in front and one comma after. A sublist inside a main list becomes flattened out into the main list. In the interpolation process, the order of the sublist is maintained. In this code, after the interpolation, the value 15 is at index 3.

If the list was a hash literal, then the order of the value pairs will be maintained. However, if the list was a hash variable, the order of the value/pairs in the hash sublist might not be maintained. Try the following code:

use strict;

    my @arr = ('pen', 'book', (Apple => "purple", Banana => "yellow"), 'ruler', 'computer');

    print $arr[4];

Here, Banana is at index 4 and the out put is, Banana.

The sublist can be an array variable, if the sublist had been assign to the array variable. In the case of the array variable, the order of the array values is maintained. Try the following code:

use strict;

    my @subL = ('aa', 15, 'cc');
    my @arr = ('pen', 'book', @subL, 'ruler', 'computer');

    for (my $i=0; $i<@arr; ++$i)
        {
            print $arr[$i], "\n";
        }

The output is:

pen
book
aa
15
cc
ruler
computer

The sublist can be a hash variable, if the sublist had been assign to the hash variable. In the case of the hash variable, the order of the hash key/value pairs may not be maintained. Try the following code:

use strict;

    my %subL = (Apple => "purple", Banana => "yellow");
    my @arr = ('pen', 'book', %subL, 'ruler', 'computer');

    for (my $i=0; $i<@arr; ++$i)
        {
            print $arr[$i], "\n";
        }

In my computer, the output was:

pen
book
Banana
yellow
Apple
purple
ruler
computer

The order of a key and its value will always be maintained, but the order of the pairs may not be maintained.

The null List
The null list or the undefined list is the empty list, (). A sub null list in a main list, is as if there was no sub list. Try the following code:

use strict;

    my @arr = ('pen', 'book', (), 'ruler', 'computer');

    for (my $i=0; $i<@arr; ++$i)
        {
            print $arr[$i], "\n";
        }

The output is:

pen
book
ruler
computer

Even if the sublist was an empty array or empty hash variable, the effect would still be as if there was no sublist.

Assigning a List to a List
You can assign a list to a list, but you have to be careful. If the number of items on the right hand side is equal to the number of items on the left hand side, then there is no problem as the following multi-statement declaration illustrates:

    my  ($a, $b, $c) = (11, 22, 33);

If the number of items on the right hand side is more than the number of items on the left hand side, then you have to decide on which items you do not want, and receive them on the left hand side with the undef value. Consider the following:

    my  ($a, undef, $b, undef, $c) = (11, 22, 33, 44, 55);

In this statement, 11 is assigned to $a. 22 is not needed so it is assigned to undef. 33 is assigned to $b. 44 is not needed so it is assigned to undef. 55 is assigned to $c. The list on the right hand side may be returned by a function. Here, undef behaves in an exceptional way (being assigned to). If you do not do this, then some of the values in the right hand list, will be assigned to wrong variables (or to undefs).

If the number of items in the list on the left hand side is more than that in the list on the right hand side, then the first corresponding items will be assign and the rest of the variables on the left hand side will have the undef value. Consider:

    my  ($a, $b, $c, $d, $e) = (11, 22, 33);

Here, $d and $e each acquire the undef value.

In the above examples, you can have arrays in the left hand side but any array becomes flattened out and each array element becomes a variable in the list. You can also have a function call in the right hand list. If the function returns one value, then the value becomes an item in the list, if the function returns a list, the values of the return list fits themselves as items in the main list.

Hash
In simple terms, a hash is a list assigned to a hash variable, and in the list the items exist in pairs. The following statement creates a hash:

    my %fruitColor = ("Apple", "purple", "Banana", "yellow", "Pear", "green", "Lemon", "green");

All the items are separated by commas. However, they are paired. Under this condition any key, which is not a number must be in quotes. The => operator has two purposes: first it makes the key/value pair more readable, as follows:

    my %fruitColor = ("Apple"=>"purple", "Banana"=>"yellow", "Pear"=>"green", "Lemon"=>"green");

It replaces the comma between a key and its value. The second purpose is that, if the left operand is a single word, its quotes can be removed and it will still be interpreted as a string (key). The following statement illustrates this:

    my %fruitColor = (Apple =>"purple", Banana =>"yellow", Pear =>"green", Lemon =>"green");

Whether the => operator is used or not, the quotes are optional when accessing a value as in $ha{Apple}; there are no quotes around Apple. So the following expression to access the “yellow” is Okay:

    $fruitColor{Banana};

Note that just because a hash is initialized in an order, does not mean that it comes out in that order. Always remember that a hash is an unordered list of pairs.

Slice
A slice accesses several elements of a list, an array, or a hash simultaneously using subscripts. A slice does not cut off any portion of the original list. It copies the values and can return the sublist of the values. The returned sublist can be assigned to a new list.

Consider the following list:

        ('pen', 'book', 'ruler', 'computer', 'pencil', 'flash disk')

If you want to access just the second value, your subscript will be [1]. If you want to access the second value, the fourth value and the sixth value, your subscripting will be [1,3, 5]. If you want to access a range of values (consecutive values), say from  'book' to 'pencil', the subscripting will be [1..4] .

Slicing a hash is a bit different. To slice a hash, you use the array variable, but with the hash subscripts. Consider the hash,

%fruitColor = (Apple=>"purple", Banana=>"yellow", Pear=>"green", Lemon=>"green");

To obtain the slice values of Apple and Pear, you can use the array variable,

    @fruitColor{'Apple', 'Pear'}

Here the keys have to be in quotes.

Try the following code:

use strict;

    my @items = ('pen', 'book', 'ruler', 'computer', 'pencil', 'flash disk')[1,3,5];
    print  @items, "\n";

    my @arr = ('pen', 'book', 'ruler', 'computer', 'pencil', 'flash disk');
    print @arr[1..4], "\n";

    my %fruitColor = (Apple=>"purple", Banana=>"yellow", Pear=>"green", Lemon=>"green");
    print @fruitColor{'Apple', 'Pear'};

Note that when you print a list, or an array or a hash or a slice, the values at the output are not separated, everything being equal.

When obtaining the slice of an array, you use the variable of the main array (including @) but with subscripts. When obtaining the slice of a hash, you use the name of the hash variable, but with @, and hash subscripts.

Slicing is more convenient than writing out the individual elements as a list of separate scalar values.

That is it for this part of the series. We take a break here and continue in the next part.

Chrys

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

BACK NEXT

Comments

Become the Writer's Fan
Send the Writer a Message