Perl Scalars

A scalar contains a single unit of data. It is preceded with a ($) sign followed by letters, numbers and underscores.

A scalar can contain anything a number, floating point number, a character or a string.

We can define scalars in two ways. First, we can declare and assign value together. Second, we will first declare and then assign value to the scalar.

In the following example, we'll show both the methods to define scalars.

Example:

Output:

Red
Delhi

Perl Scalar Operations

In this example we'll perform different operations with two scalar variables $x and $y. In Perl, operator tells operand how to behave.

Example:

Output:

5
3
8
53
555

The first and second output is the value of $x and $y respectively.

(+) operator simply adds 5 and 3 giving the output as 8.

(.) is a concatenation operator which concatenates the output 5 and 3 giving the output as 53.

(x) is a repetition operator which repeats its left side variable as many times as the number on its right side.

Perl Special Literals

There are three special literals in Perl:

__FILE__ : It represent the current file name.

__LINE__ : It represent the current line number.

__PACKAGE__ : It represent the package name at that point in your program.

Example:

Output:

File name hw.pl
Line Number 6
Package main
__FILE__ __LINE __ __PACKAGE

Perl String Context

Perl automatically converts strings to numbers and numbers to strings as per the requirement.

For example, 5 is same as "5", 5.123 is same as "5.123".

But if a string has some characters other than numbers, how would they behave in the arithmetic operations. Let's see it through an example.

Example:

Output:

7
52cm
55

In numerical context, Perl looks at the left side of the string, and convert it to the number. The character becomes the numerical value of the variable. In numerical context (+) the given string "2cm" is regarded as the number 2.

Although, it generates warning as

What has happened here is, Perl does not convert $y into a numerical value. It just used its numerical part i.e; 2.


Perl undef

If you'll not define anything in the variable, it is considered as undef. In numerical context, it acts as 0. In string context, it acts as empty string.

Output:

Use of uninitialized value $y in addition (+) at hw.pl line 9.
5
Use of uninitialized value $y in concatenation (.) or string at hw.pl line 10.
5
Use of uninitialized value $y in repeat (x) at hw.pl line 11.
NOT
Next TopicPerl Operators