Perl: Operations and Assignments

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


Perl uses all the common assignments:

$a = 1 + 2; # Add 1 and 2 and store in $a
$a = 2 - 4; # Subtract 4 from 2 and store in $a
$a = 2 * 4; # Multiply 2 and 4
$a = 1 / 2; # Divide 1 by 2 to give 0.5
$a = 2 ** 10;# 2 to the power of 10
$a = 5 % 2; # Remainder of 5 divided by 2
++$a; # Increment $a and then return it
$a++; # Return $a and then increment it
--$a; # Decrement $a and then return it
$a--; # Return $a and then decrement it

Also, we can do concatenation as follows: $a="this "."binds"; would store "this binds" in $a. In the following program,

$saySomething = "this is me";
$a = "me";
$b="this";
$combine = $a." is ".$b;
$takeLiterally = '$a is $b';

$a and $ b are same. Double quotes (") forces the variable parameters to be interpolated and evaluated. When the string is captured in single quotes, it is literally taken without any evaluation, therefore , $takeLiterally would return "$a and $b" while $combine would store "this is me". Thus, double quotes forces interpretation of variables, special charaters like new line (\n), new tab(\t). Note again here, that the concatenated variables can be numbers as well. Therefore, $a = 1.2 would make $a = 12. Other assignment variables in perl are:

$a = $b; # Assign $b to $a
$a += $b; # Add $b to $a
$a -= $b; # Subtract $b from $a
$a .= $b; # Append $b onto $a




Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.