Broad Network


Perl Predefined Array Functions

Using Perl Arrays – Part 2

Perl Course

Foreword: In this part of the series, I talk about Perl predefined array functions.

By: Chrysanthus Date Published: 30 Oct 2015

Introduction

This is part 2 of my series, Using Perl Arrays. In this part of the series, I talk about Perl predefined array functions. You should have read the previous part of the series before coming here, as this is a continuation.

Slicing an Array
Slicing an array means obtaining the values of a range of elements in the array. To do this, you begin with the @ sign. This is followed by the name of the array; then square brackets. Inside the square brackets, you begin with the index of the start element of the range, then two dots and then the index of the end element of the range. Here, a range means consecutive elements in the array. If the number of elements in the range is small, say two, three or four, then you can type their indices in the square brackets separating them with commas and you would not need the two dots.

@arr[0,1] obtains the values of the elements at index 0 and 1 from the array, @arr. @arr[3..8] obtains the values of the array elements from index 3 to 8 inclusive (including those for 3 and 8). @arr[14..$#arr] obtains the values of the array elements from index 14 to the end of the array, where $#arr means the last index of the array for @arr.

Read and try the following code:

use strict;

my @arr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

print @arr[0,1,2]; print "\n";
print @arr[2..6]; print "\n";
print @arr[5..$#arr];

If you had tried the code, you would have noticed that the displayed values are not separated by commas. Do not worry about that for now.

Slicing can actually be more complex than this: precisely, you can slice discontinued ranges from the array. For this basic tutorial, we shall not go into that.

Difference between @array[1] and $array[1]
@array[1] is an array slice of one element, while $array[1] is an array element. When you just want an array element, use $array[1] .

The push Function
Consider the array,

@hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

The name of the array here is @hisArr. Also consider the list,

("xxx", "yyy", "zzz")

In Perl a list is given in normal brackets. You can append (add to the end) the three elements (values) of the list to the array. The syntax to do this is:

    push (ARRAY, LIST)

In our example, you would have,

    push (@hisArr, ("xxx", "yyy", "zzz"));

Read and try the following code:

use strict;

my @hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

push (@hisArr, ("xxx", "yyy", "zzz"));

print @hisArr;

The output of the code shows the appended list. Well, the items of the output are not separated by commas. Do not worry about that for mow. The push function returns the new number of elements in the resulting array.

The unshift Function
The unshift function does the opposite of the push function. It prepends a list in front of the array, returning the new number of elements in the resulting array. The syntax is:

    unshift (ARRAY, LIST)

In our case, you would have,

    unshift (@hisArr, ("xxx", "yyy", "zzz"));

Read and try the following code,

use strict;

my @hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

unshift (@hisArr, ("xxx", "yyy", "zzz"));

print @hisArr;

The pop Function
The pop function removes the last element from the array and returns it, shortening the original array by one element. The syntax is,

    pop (ARRAY);

In our case, you would have,

    pop (@hisArr);

Read and try the following code:

use strict;

my @hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

my $returnValue = pop (@hisArr);

print $returnValue; print "\n";
print @hisArr;

The fourth statement, pops of the last element from the array assigning the value removed to the new variable, $returnValue. The last-but-one line displays the returned (removed) value. The last line displays the original array, which is now missing its last element.

The shift Function
The shift function does the opposite of the pop function. It removes the first element from the array and returns it, shortening the original array by one element. The syntax is

    shift (ARRAY);

In our case, you would have,

    shift (@hisArr);

Read and try the following code:

use strict;

my @hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

my $returnValue = shift(@hisArr);

print $returnValue; print "\n";
print @hisArr;

The space between any function name and its opening bracket is optional. In the previous case, there is a one space character between pop and (. In the above case, there is no space character between shift and (; it is optional.

The splice Function
The splice function removes a portion (range) of elements from the array and replaces them with that of some list, if it is present. The resulting array may be larger or smaller than the original array depending on how many elements are in the replacement list. If there is no list, then the resulting array is shorter. The splice function returns the removed list. The syntax is,

    splice (ARRAY, OFFSET, LENGTH, LIST)

ARRAY is the name of the original array. OFFSET is the index at which the removal will start. Remember, index counting begins from zero. LENGTH is the number of consecutive elements to be removed. LIST, if present has the elements to replace the ones removed.

For our example, imagine that you want to remove 3 elements beginning from index 5 (which is position 6) and replace them with the list, ("xxx", "yyy", "zzz"). The splice function would be,

    splice (@hisArr, 5, 3, ("xxx", "yyy", "zzz"));

Read and try the following code:

use strict;

my @hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

print splice (@hisArr, 5, 3, ("xxx", "yyy", "zzz")); print "\n";

print @hisArr;

The third line has the splice function. This statement for the splice function is preceded by the command (another function), which is “print”. The splice function returns the removed list. From the splice statement, as the return list is returned, it is printed (displayed) by the print function. The last line in the code displays the resulting original array. Remember, if the list is not present in the splice function, the resulting original array would not have a replacement.

The use of the splice function can be more complicated than what I have explained. For this basic tutorial, let us allow things like this.

Replacing List as Array for push Function
In all the functions, we have had list consisting of elements, delimited brackets. You can replace a list with an array. Read and try the following code:

use strict;

my @hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

my @herArr = ("xxx", "yyy", "zzz");

push (@hisArr, @herArr);

print @hisArr;

The third line creates a new array (list) that is to be appended by the push function. The fourth line has the push function and in place of a list of elements, it has the array variable. The last line prints the resulting array.

The Four Array Functions on @_
You can use the array operators (functions), push, pop, shift, and unshift on @_. You should already know how to use these operators on any array. The use is the same here. So, I illustrate the use, only with the shift() predefined function (operator). Consider the following code, which adds two numbers and prints the sum:

use strict;

    sub myFunc;

    sub myFunc
        {
            my $var1 = $_[0];
            my $var2 = $_[1];
            my $var3 = $var1 + $var2;
        }

    my $ret = myFunc 20, 30;
    print $ret;


The above code can be modified as follows:

use strict;

    sub myFunc
        {
            my $var1 = shift @_;
            my $var2 = shift @_;
            my $var3 = $var1 + $var2;
            print $var3;
            return;
        }

    myFunc(20, 30);

The shift function removes the first element of the @_ array and returns the value, making the second element the new first element. The four operators are the default operators for the @_ array; so inside a function definition, you do not really need to type @_ as argument to the four operators. So, the following code works fine:

    sub myFunc
        {
            my $var1 = shift;
            my $var2 = shift;
            my $var3 = $var1 + $var2;
            print $var3;
            return;
        }

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