Basic Operators and Control Flow

Scalar Variable

The definition of a scalar variable is that it stores one item (line of input, piece of text, number), the name of a scalar variable starts with a \$ sign and must be followed by at least one letter

 Good Names \$x \$var \$total_value \$x1234 \$this_is_a_very_long_name_but_legal Bad Names \$              - there must be at least one letter in the name \$47x          - the second character must be a letter \$var!         - you cannot have ! in a variable \$new.var   - you cannot have a . in a variable

Perl variables are case sensitive

 All different variables \$var \$Var \$VAR

You assign values to variable but using the assignment operator =

 Assigning values \$var = "Hello World!"; \$total_salary = 13000; Note: do not forget the semi-colon at the nd to terminate the statement

Performing Arithmetic

Perl uses the basic arithmetic operators

 Arithmetic operators +     - addition -     - subtraction /     - divison *     - Multiplication Examples \$var = 7 + 5; \$var = 30 - 8; \$var = 20 - 5 * 10; \$var = 16; \$var_total = \$var - 6 + 10;

Conditional Statements

Perl uses conditional statements if, while and until

 IF Statement if (\$number) { print "The number is not zero"; } if (\$number == 21 ) { print "The number is 21 "; } IF-ELSE statement if (\$number1 == \$number2) {        print "The two numbers are equal"; } else {        print "The two numbers are not equal"; } IF-ELSIF-ELSE statement if (\$number1 == \$number2) {        print "Number1 is equal to number2"; } elsif (\$number1 == \$number3) {        print "Number1 is equal to number3"; } elsif (\$number1 == \$number4) {        print "Number1 is equal to number4"; } else {        print "Number1 does not match any number "; } While Statement \$number = 1; while (\$number != 5) {     print ( "The number is still not 5\n");     \$number = \$number + 1; } Note: There is a possibility that the while loop will not run if the condition has already been meet. Until Statement \$number = 5; until (\$number == 5) {    print "Number is not 5 yet!\n";    \$number = \$number +1 ; } Note: in other languages until loop always runs at least once but perl is different, if the conditional statement has already been meet then the until loop will not run as shown above

See More Control Structures for information on single-line conditional statements, loops and the goto statement.