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.
use strict; use warnings; use 5.010; #Declairing and assigning value together my $color = "Red"; say $color; #Declairing the variable first and then assigning value my $city; $city = "Delhi"; say $city;
In this example we'll perform different operations with two scalar variables $x and $y. In Perl, operator tells operand how to behave.
use strict; use warnings; use 5.010; my $x = 5; say $x; my $y = 3; say $y; say $x + $y; say $x . $y; say $x x $y;
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.
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.
use strict; use warnings; use 5.010; #!/usr/bin/perl print "File name ". __FILE__ . "\n"; print "Line Number " . __LINE__ ."\n"; print "Package " . __PACKAGE__ ."\n"; # they can?t be interpolated print "__FILE__ __LINE__ __PACKAGE__\n";
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.
use strict; use warnings; use 5.010; my $x = "5"; my $y = "2cm"; say $x + $y; say $x . $y; say $x x $y;
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
Argument "2cm" isn't numeric in addition (+) at hw.pl line 9.
What has happened here is, Perl does not convert $y into a numerical value. It just used its numerical part i.e; 2.
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.
use strict; use warnings; use 5.010; my $x = "5"; my $y; say $x + $y; say $x . $y; say $x x $y; if (defined $y) { say "defined"; } else { say "NOT"; }