In general as any other programmimg language, variable names consists of numbers,
letters and underscores, but they should not start with a number. And the variable
$_ is special variable. Perl is case sensitive, so both the variables $a and $A are
different.
Perl Scalar Variables
The most basic type of variable in Perl is the scalar variable. Scalar variables hold
strings and numbers both, and are remarkable as the strings and numbers are completely
interchangable. For example cosider the following statement
$priority = 9;
This statement sets the scalar variable $priority to the value 9, but you can also
do assign a character string to the same variable:
$priority = 'high';
Perl accepts numbers as strings, as shown below:
$priority = '9';
$default = '0009';
It can still cope with arithmetic and other operations quite happily.
Perl Operations and Assignment
Perl uses almost all the C arithmetic operators:
$x = 1 + 2; # Add 1 and 2 and store it in $x
$x = 4 - 3; # Subtract 4 from 3 and store in $x
$x = 5 * 6; # Multiply 5 and 6
$x = 7 / 8; # Divides 7 by 8 to give 0.875
$x = 9 ** 10; # Nine to the power of 10
$x = 5 % 2; # Remainder of 5 divided by 2
++$x; # Increment $x and then return it
$x++; # Return $x and then increment it
--$x; # Decrement $x and then return it
$x--; # Return $x and then decrement it
For strings Perl has the following operations:
$x = $y . $z; # Concatenate $y and $z
$x = $y x $z; # $y repeated $z times
Note: when Perl assigns a value with $x = $y it makes copy of $y and then
assigns it to $x. Therefore when you change $y the next time it will not alter $x.
Perl Interpolation
The following fragment prints apples and pears using concatenation operation:
$x = 'apples';
$y = 'pears';
print $x.' and '.$y;
It would be nice to include only one string in the print statement, but in the line below,
print '$x and $y';
prints literally $x and $y which is not that helpful. Instead of this we can use double
quotes in the place of the single quotes:
print "$x and $y";
here the double quotes force the interpolation of any codes, including variable interpreting.
This is much better than our original statement. Other codes which are interpolated
includes some special characters such as newline and tab. The code \n is a newline character
and \t is tab.
Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.