Broad Network


Perl Variables

Perl Data Types – Part 1

Perl Course

Foreword: In this part of the series, I talk about Perl variable types.

By: Chrysanthus Date Published: 22 May 2015

Introduction

This is part 1 of my series, Perl Data Types. In this part of the series, I talk about Perl variable types. A variable in Perl, is an identifier that identifies an entity. Different types of entities have different ways in which their variables are typed.

Pre-Knowledge
This is part of a volume called, Perl Course. The links to the different series in this volume in the order in which you should study, are given at the bottom of this page. You must study the course in the order in which the series are given. This is actually the second series in the volume. You must have read the first series titled, Perl Basics, before reaching here.

Data Types
Perl has three data types called: scalar, array and hash. Data types are not really variable types, as you will discover in this tutorial. You should already have a notion on scalar, array and hash, if you have read the previous series.

A scalar is a single value. This value can be a number, string or reference. An array is a list of scalars, held by a variable. A hash is also a list, but a list of scalar pairs held by a variable; the second scalar value for each pair is accessed using the first scalar value (for the pair).

The elements of the array are indexed from 0. The elements of the hash are indexed by the first scalar value of each pair. The first scalar value of each pair is called the key.

The variable of any scalar begins with $, as in the variable, $item. The variable of any array begins with @, as in the variable, @arr. The variable of any hash begins with % as in the variable, %ha.

The variables of certain entities, do not have any preceding special symbol such as $ or @ or %. Whether a variable has a preceding special symbol or not, the text part of the variable name must begin with a letter or an underscore. The rest of the text can be a combination of letters, underscores and digits.

Perl has special built-in variables, whose names do not follow this rule. There are two categories of these special built-in variables: the ones involved in what is known as Regular Expressions, and the ones for the inner workings of Perl. The ones for regular expressions are scalars: a scalar here begins with $ and is followed by a number. The ones for the inner workings of Perl are of different entity types, and the text part of the name can have punctuation characters and control characters.

Scalar variables are always named with $, even when referring to a scalar that is part of an array or a hash. An example of a scalar name is $arr. To access the third value (scalar) of an array, you would type something like, $arr[2], where the array variable name is, @arr. If the key of a key/value pair of a hash is BB, then to access the value (scalar) in the hash, you would type something like, $ha{'BB'}, where the hash variable name is, %ha.

Function Type
In Perl, a function is called a subroutine. You define a function beginning with the reserved word, sub. This is followed by the variable (name) of the function; then you have a block containing the statements. The variable of a function should begin with, &. However, you can omit & where there will be no ambiguity. In the following two code segments, the two function calls mean the same thing, and both work:

    sub funct
        {
            print "seen";
        }
    funct();

    sub funct
        {
            print "seen";
        }
    &funct();

In most situations, the omission of & does not produce any ambiguity.

Bareword
Any isolated word such as “item” not preceded by $ or @ or % or &, found arbitrarily in a Perl program code, is called a bareword. Its presence is an error. There are some variables that are not preceded by $ or @ or % or &. Such variables are found in particular positions in the program code; they are not barewords, because of the situations in which they are found.

Same Text Part for Different Variable Types
Each kind of entity corresponds to a variable type. Each variable type is said to have what is called a namespace. So there is no conflict in naming, so far as variable types are concerned. For example, $foo, @foo, %foo and &foo are different variables for different entities (types) and pose no name conflict. All of these variables can be found within a function block, or other blocks.

Label
You can identify a point in a program code using a variable type called, label. A label is a word followed by a colon. It is not preceded by $ or @ or % or &. It is not a bareword, because it is followed by a colon. Consider the following program:

use strict;

    my $counter = 0;

    Again:
        print "seen\n";

    if ($counter == 2)
        {
            goto Stop;
        }

    $counter=$counter + 1;
    goto Again;

    Stop:

If you try this program, the output will be:

seen
seen
seen

As the program is running through, the first time from the top, it meets the label, “Again:” and then it prints “seen”. The execution continues downward; it then meets the if-construct; the condition is false and the if-block is skipped. Then the counter is incremented. Then it meets the statement, “goto Again;”. goto is a command, that tells the execution to go to the label and start re-executing from there and coming down.

For the program, the looping execution continues until the if-condition is satisfied, executing the if-block. The block has only one statement that sends execution to the label, “Stop:” at the bottom of the script. From there, the execution goes downward and ends.

That is one way of using the label variable. The label does not only have to be used with the goto command. The label can be used to identify a loop such as the for-loop (see later).  

File Handle
A file handle written as filehandle, is a variable used for accessing a file in a computer disk. Consider the following code segment for reading the content of a file:

if (open(fHandle, "< myfile.txt"))
    {
        my @lines = <fHandle>;

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

        close (fHandle);
    }

The filehandle here is fHandle. A filehandle variable, is text of your choice, without any $ or @ or % or &. It cannot be typed anywhere in a program. It must be type within certain expressions. The expressions for the filehandle above are: “open(fHandle, "< myfile.txt")”, “<fHandle>” and “close (fHandle)”.

The variable is not a bareword, because it is not typed anywhere in the program code. It is typed in particular expressions. Note: it is conventional to type filehandles in Perl in uppercase.

Conclusion
There are eight variable types in Perl: scalar, array, hash, function, label, filehandle, typeglob and format. I have explained above, how to code them, except for typeglob and format. I will explain these two later.

Do not confuse between data types and variable types. There are three data types, which are scalar, array and hash, and each of these types has its own variable type. However, there are eight main entities (accessible features) in Perl, some of which do not fit in the light of scalar, array and hash. Each of these entities has its own way of coding its variable.

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

NEXT

Comments

Become the Writer's Fan
Send the Writer a Message