Scalar Variable is a simple data that can be manipulated very easily by Perl. Numbers and Strings are basic scalar variables.
Number:
In Perl, integers can be expressed in decimal (base 10), hexadecimal (base 16) or octal (base 8) notation. Octal numbers are preceded by a 0 (zero).Perl internally considers integer as a double precision floating point value. Integer cannot be delimited by comma instead Perl allows underscore to seperate inetegers.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
#floating-point values
$x = 4.15;
$y = -7.78;
#integer values
$a = 4000;
$b = -20;
print "$xn";
print $a;
Result :
4.15 4000
The number can also accept a string ie., $a=20 is similar to $a="20".
String:
The string defines a sequence of characters which can be defined in a single or double quotes.But when using Double quotes one has to carefully use the escape character "\" to get the correct display.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
print "Sam says, "Give me $200".";
Result :
Server Error!
In the above example "$" is used for variable substitution and also as a symbol.Perl will assume that the string ends at the second double quotes. To get the correct display the string has to be escaped as below.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
print "Sam says, \"Give me $200\".";
Result :
Sam says, "Give me $200"
If single quotes is used no need to escape a string as below.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
print 'Sam says, "Give me $200".';
Result :
Sam says, "Give me $200".
String Concatenation:
In perl strings can be concatenated using the concatenation operator ".", but if the string contains quotes, carriage returns, backslashes, all these special characters need to be escaped with a backslash.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
$a = "Hiox, India's";
$c = "Hosting Company";
$concat = $a ." leading Web". $c;
print $concat;
Result :
Hiox, India's leading WebHosting Company
In the above example the strings "$a", "$b","$c" is concatenated using the "." operator.
Variable Substitution:
Variable substitution means that variables within a double-quoted string will be substituted by their values at the time the statement is evaluated.This is not allowed when using a single quote, but when double quotes is used variable substitution is accepted.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
$cel=40;
$fah = ($cel * 1.8) + 32;
print "The $cel degrees Celsius is $fah fahrenheit n";
print 'The $cel degrees Celsius is $fah fahrenheit ';
Result :
The 40 degrees Celsius is 104 fahrenheit
The $cel degrees Celsius is $fah fahrenheit
In the above example first the value of the variables "$cel","$fah" are substituted as its given between double quotes. In the second print statement the string is given within single quotes so "$cel","$fah" is printed as it is.