Broad Network


Searching and Shuffling a Perl Array

Using Perl Arrays – Part 4

Perl Course

Foreword: In this part of the series, I explain how to find the first array element for which a condition is true; how to determine if a certain element is found in an array. I also explain how to select a random element from an array and how to shuffle an array randomly.

By: Chrysanthus Date Published: 30 Oct 2015

Introduction

This is part 4 of my series, Using Perl Arrays. In this part of the series, I explain how to find the first array element for which a condition is true; how to determine if a certain element is found in an array. I also explain how to select a random element from an array and how to shuffle an array randomly. You should have read the previous parts of the series before reaching here, as this is a continuation.

First Array element for which a Condition is true
In this section I explain how to find the first array element for which a condition is true. It is simple: just use a foreach loop with regular expression (or some other scheme) to iterate through the array and stop the iteration with the last command, when you see the element. The following code illustrates this; it looks for the first element that has “apple”:

use strict;

    my @fruits = ("pear", "orange", "banana", "pineapple", "lime", "apple", "lemon");

    my $found;
    foreach (@fruits)
        {
            if(/apple/)
                {
                    $found = $_;
                    last;
                }
        }

    print $found;

The output is,

    pineapple

The if-condition in the code is, (/apple/). In a foreach loop, it actually means ($_ =~ /apple/). Instead of identifying the element found, you can identify the index, as the following code shows:

use strict;

    my @fruits = ("pear", "orange", "banana", "pineapple", "lime", "apple", "lemon");

        my( $found, $index ) = ( undef, -1 );

        foreach my $i (0..$#fruits)
            {
                if($fruits[$i] =~ /apple/)
                    {
                        $found = $fruits[$i];
                        $index = $i;
                        last;
                    }
            }

    print "'$found' at index, $index";

The output is:

    'pinapple' at index, 3

Checking if an Element is in an Array
In this section I explain how you can tell whether a certain element is contained in a list or array? It is simple: use the smart match operator. The smart match operator is ~~ . It means, in, in this context. Use it in an if-condition. The if-condition will return true if the item is in the array, or false if the item is not.

use strict;

    my @fruits = ("pear", "orange", "banana", "pineapple", "lime", "apple", "lemon");

    my $item = "lime";

    if($item ~~ @fruits)
        {
            print "$item is in the array.";
        }
    else
        {
            print "$item is not in the array.";
        }

The output is:

    lime is in the array.

This search is case sensitive.

You could have scanned the array with a foreach loop to see if the item is there. However, that would not be mature enough.

Selecting a Random Element from an Array
To select a random element from an array, use the predefined rand() function as follows:

        my $index   = rand @array;
        my $element = $array[$index];

where the random index is first returned and then the index is used to return the element. A shorter form of the above two statements is:

        my $element = $array[rand @array];

Try the following code:

use strict;

    my @fruits = ("pear", "orange", "banana", "pineapple", "lime", "apple", "lemon");

    my $element = $fruits[rand @fruits];

    print $element;

I tried the code in my computer and I had,

    orange

Since it is random, yours will be different.

Shuffling an Array
To shuffle an array, use a module that is installed with Perl as the following code illustrates:

use strict;

use List::Util 'shuffle';

    my @fruits = ("pear", "orange", "banana", "pineapple", "lime", "apple", "lemon");

    my @shuffled = shuffle(@fruits);

    print "$_ " foreach @shuffled;

Note the statement, “use List::Util 'shuffle';” and its function, shuffle() that it brings. I tried the code in my computer and I had:

    orange lime apple pineapple lemon banana pear

Since it is shuffling, your own output will be different.

That is it for this part of the series. We stop 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