Broad Network


Scalar Values in Perl

Perl Data Types – Part 2

Perl Course

Foreword: In this part of the series, I talk about Perl scalar values.

By: Chrysanthus Date Published: 22 May 2015

Introduction

This is part 2 of my series, Perl Data Types. In this part of the series, I talk about Perl scalar values. You should have read the previous part 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 may contain one single value in any of three different flavors: a number, a string, or a reference. Although a scalar may not directly hold multiple values, it may contain a reference to an array or hash, which in turn contains multiple values.

Transparent Conversion of Scalar Values
A variable holding a number can be changed to hold a string and can still be changed to hold a reference. The following code illustrates this but such changing is no good programming practice:

use strict;

    my $item = 55;
    print $item, "\n";

    $item = "I love you.";
    print $item, "\n";

    my $myVar = "We are the world.";
    my $item  = \$myVar;
    print ${$item}, "\n";

The output of this code is:

    55
    I love you.
    We are the world.

In the following code, addition takes place:

    my $result = "  22  " + 4;
    print $result;

Here, the string, "  22  " has been converted into a number before adding. If a string consists of a number, optionally preceded or followed by whitespace, in an arithmetic operation, it would be converted into a number. Correct addition would not be possible, if the number in the string had some alphabet letters within its characters, as in "  2G2  "

null
null means nothing. In Perl, the value for null is the literal, undef. In other computer languages it is, null. In the following statement, the value of $item is 25.

    my $item = 25;

Here, $item is said to be defined, because it has a value.

In the following statement, the value of $item is undef.

    my $item;

Here, $item is said to be undefined because it has not been given a value. Well, the value is actually undef, meaning undefined.

To know whether a value is defined or not, use the defined() function as in the following code:

    my $item = 25;
    if (defined($item))
        {
            print "Yes";
        }

The output is “Yes”, because $item has been assigned a value, so defined($item) produces true. It would have produced false, if $item had not been assigned any value.

If a variable is defined, you can undefine it giving it the value, undef, using the undef() function as in the following code:

use strict;

    my $item = 32;
    undef($item);

    print $item;

The undef value cannot be printed. So, nothing is printed for this output.

Array
An array is a list of scalars held by a variable, beginning with @. A list that is not held by the variable is not really an array. The items in the array are indexed beginning from zero. Since each value is a scalar, to access a value, you have to use the scalar symbol, $. This is followed by the text name of the array and then a subscript in square brackets. The subscript for the array value is an integer (index) in opposite square brackets. This index can be a variable, which will expand (be replaced) to the integer. The following code has an array of items, which are on a table. The second item is read.

use strict;

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

    print $arr[1];

The position (index + 1) of the last-but-one item in an array can be obtained with the following syntax:

    $#arrayName

The following code illustrates this:

use strict;

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

    print $#articles;

The output is 3.

There is no Perl function to obtain the length of an array. The length of the array is obtain by operating the array in scalar context as the following code illustrates:

use strict;

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

    my $len = @articles;

    print $len;

In this code, the statement for the scalar context is:

    my $len = @articles;

The array variable with its @ symbol has been assigned to a scalar, $len. Such an operation returns a scalar; in this context the scalar is the length of the array (which in this case is 4). The operator involved here is the assignment operator.

The following code illustrates another situation in which the array is operated in the scalar context:

use strict;

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

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

The scalar context operation here is the condition,

    $i<@articles

In front of < you have a scalar, $i. The array variable with its @ is forced to return a scalar. In this situation, it is the length of the array, which is compared to the $i scalar value, by the < operator.

Note: in Perl you can assign a value to an array index that is beyond the last index. The values between the last index and that of the new index will be undef. The following code illustrates this:

use strict;

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

    $articles[7] = 'smartphone';

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

If you tried the code, you would have noticed that the undef values were not printed (displayed). Also, the length of the array was increased. To assign a value beyond the current last index, you just decide on an index and then you assign the value, as the third statement above shows.

Hash
An array is an ordered list of scalars. On the other hand, the hash is an unordered list. It is an unordered list of key/value pairs. In the list each key is always followed by its value. However, for the same hash, in different situations the order of the pairs can be different. A list with key/value pairs is not really a hash, the list has to be held by a hash variable, which begins with %.

There is no function for obtaining the length of a hash. However, there is a workaround. Remember the keys() function for the hash, whose syntax is given as:

    keys (%hashName)

This function returns an array of all the keys in the hash. The length of this array is the length of the hash. So, place this returned array in a scaler context to obtain the length of the hash, as the following code illustrates:

use strict;

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

    my @kiys = keys(%fruitColor);
    my $len = @kiys;
    print $len;

The output is 4, for the 4 pairs in the hash.

Since the hash is an unordered list, you cannot talk of including a key/value pair beyond the current limit. However, after creating a hash, you can always include a pair, to the hash. The following code illustrates this:

use strict;

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

    $fruitColor{lime} = "light green";
    
    print $fruitColor{lime};

To achieve this, you just decide on a key and then you assign the value, as the last statement in this code shows.

A hash is made up of scalars. The scalars are paired. In each pair, the first scalar is called the key and the second is called the value. Between the key and value, the real interest is the value. So, the subscript for a hash value is the key in curly brackets, as opposed to integer in square brackets for the array. Since you are to access the scalar value, the variable to access the scalar value has to begin with the scalar symbol, $. This is followed by the text name of the hash; then the subscript in curly brackets.

In scalar context, a hash returns 0 for false if it is empty, and 1 for true if it is not empty.

In this part of the series, I have explained to you Scalar Values. 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. In the next part of the series, I will talk about scalar value constructions. See you there.

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