Basic Scalar Operations
#!/usr/bin/perl -w
######################## Scalar Operations Demo #########################
print "\007\n"; ####### Octal for ASCII bell character.
$var = "20";
$newvar = $var ** 2; ####### Should be 20 * 20 which is 400.
print "$newvar\n";
$newvar = $var / 3; ####### / ALWAYS does floating division. Result: 6.67
print "$newvar\n";
print $newvar / 2, "\n"; ###### Can't do arithmetic in quotes!!
use integer;
$newvar = $var/3; ####### Coerce integer arithmetic. Result: 6
print "$newvar\n";
no integer;
$newvar = $var/3; ####### Go back to floating point. Result: 6.67
print "$newvar\n";
$newvar = $var % 3; ####### 20 divided by 3 leaves remainder of 2
print "$newvar\n";
$var = "*";
print $var x 75, "\n"; ####### Prints 75 "*" characters.
$var = 0;
$var += 10; ####### $var op= value is same as $var = $var op value
print "$var\n";
$var *= 2.3; ####### Turns into a floating point result (34.5).
print "$var\n"; ####### Notice the type conversion done by Perl.
####### If results are integral, no decimal point!
print "Enter a line: ";
while (($line = <STDIN>) !~ /^\s*quit\s*$/i)
{
chomp $line;
$string .= $line;
print "Enter a line: ";
}
print "$string\n\n";
######## Relational Operators
######## For numbers: < <= > >= == !=
######## For strings: lt le gt ge eq ne
print "Enter a number: ";
while (($line = <STDIN>) < 10)
{
print $line; ##### Note that whitespace (here \n) ignored in numbers!!
print "Enter a number: ";
}
print "Enter a string: ";
while (($line = <STDIN>) lt "Noodle")
{
print $line;
print "Enter a string: ";
}
############################# Program Output ############################
$ scalars.pl
400 ######### 20 ** 2
6.66666666666667 ####### Perl gives you LOTS of decimal places.
3.33333333333333 ####### The above divided by two.
6 ######### After "use integer"
6.66666666666667 ####### After "no integer"
2 ####### Notice lack of decimal point.
***************************************************************************
10
23
Enter a line: hello
Enter a line: goodbye
Enter a line: quit
hellogoodbye
Enter a number: 8 ###### Whitespace in numbers is ignored!!
8
Enter a number: 4
4
Enter a number: 12 ###### < 10 test failed!
Enter a string: Nimrod
Nimrod
Enter a string: Foobar
Foobar
Enter a string: nimrod ####### 'n' is less than 'N'
########################### Operator Summary ############################
For examples below, assume $var's value is 5.
Example Result Operator Operator's Action
------- ------ -------- -----------------
"AB" x 3 ABABAB x Replicate string
$var++ 6 postfix ++ Add one to $var AFTER
$var's value is used.
++$var 6 prefix ++ Add one to $var BEFORE
$var's value is used.
$var-- 5 postfix -- Subtract one from $var
AFTER $var is used.
--$var 5 prefix -- Self-explanatory!!
$var."string" 5string . Concatenation.
$var *= 3; 15 *= Multiple left operand
by right operand.
$var ** 3 125 ** Exponentiation.