160 likes | 479 Views
Scalar Variables. Getting a Perl program to run. Start the file with: #! /usr/bin/perl –w No spaces or newlines before the the #! “#!” is sometimes called a “shebang”. It is a signal to the operating system to process the file using the program following it: /usr/bin/perl.
E N D
Scalar Variables Getting a Perl program to run. • Start the file with: #! /usr/bin/perl –w • No spaces or newlines before the the #! • “#!” is sometimes called a “shebang”. It is a signal to the operating system to process the file using the program following it: /usr/bin/perl. • /usr/bin/perl is the absolute path to the Perl executable file: it is in the /usr/bin directory. • the “-w” means “turn on warnings”. This causes the Perl compiler to give error and warning messages for a wide variety of problems, very useful for debugging.
General Info • Whitespace: spaces, tabs, newlines: is widely ignored by Perl. Use it generously to make it easier to read your code. • Line endings. Each Perl statement ends in a semi-colon “;”. A major exception to this is that blocks of code, enclosed by curly braces { } usually don’t need a semi-colon. • Comments. Everything on a line following a # is treated as a comment and ignored. Note that this only works for a single line. Use comments generously to make it clear what the code is supposed to do. • Multi-line comments. If the first column has a “=“ in it (I usually use “=comment”), then everything from that point down to “=cut” is treated as a comment. • File names. It is not necessary to name files with a “.pl” extension for Linux to run them. However, I usually add “.pl” just so I know that they are Perl programs.
Hello, World! • Here is a 2 line Perl program that demonstrates the fundamental capacity to execute a program: • #! /usr/bin/perl –w print “Hello, world!\n”; --the “\n” is a newline symbol: it causes a carriage return to occur. --remember to give this file execute permissions: “chmod 755 hello.pl” --run it by simply typing “hello.pl” on the command line, followed by Enter.
Literal Numbers • How to represent a number. Note that unlike in C, Perl does not require you to differentiate between integers and floating point numbers. All such conversions are handled internally by the compiler. • Integers and decimal numbers can be written as expected: 12, -2004, 98.6, etc. You can use a + or – sign to start the number if you like: +36 is the same as 36, for example. • If a number is larger enough to need internal separators: 1,000,000, for example, you must substitute underscores ( _) for the commas. In Perl, this would be written as 1_000_000. The compiler ignores the underscores. • Numbers using an exponent are written like “14e5”. This means 14 x 105. An “e” or “E” in the number means that the digits to the right are used as a base 10 exponent.
Numerical Operators • Pretty much the same as in C: +, -, *, and / for addition, subtraction, multiplication, and division. Whitespace can be used around the operators if desired. • Division is floating point: 10 / 3 = 3.333333, unlike in C. To get integer division, precede the expression with “int” (for integer). Thus, “int 10 / 3” gives 3. • Exponentiation is done using “**”. Thus 10**3 equals 1000. • The modulus operator is “%”. This gives the remainder after integer division. Thus, 10 % 3 equals 1.
Strings • Strings are a fundamental variable type in Perl (i.e. no need for character arrays as in C). • A string is any set of characters enclosed by single quotes or double quotes. • When single quotes are used, all characters are interpreted literally (printed exactly as written) except for the single quote itself ( ‘ ) and the backslash ( \ ). To get a single quote to print, you must “escape” it be preceding it with a backslash. For example: print ‘This is a single quote: \’ that prints correctly’; Similarly, to print a backslash, it must be preceded by another backslash: print ‘Backslash: \\’; • When double quotes are used, two extra things happen: “escape sequences” and variables are interpreted. That is, they are translated into other symbols and not printed literally. • Escape sequences start with a backslash. “\n” stands for a newline; it is the most common escape sequence. Another is \t (=tab). Also, to print a single quote, double quote, or backslash, the characters must be preceded by a backslash. There is a table of escape sequences on page 24. • Varaibles are substituted when printing with double quotes. We will see many examples soon.
String Operators • Concatenation (running two strings together) is done using the dot ( . ). “the” . “ “ . “dog” is interpreted as “the dog” • String repetition operator is “x”. For example, “fred” x 4 = fredfredfredfred. • Numbers and strings are the two main types of scalar variable. They are freely interconvertible • Thus, “5” and 5 are the same thing. • Non-numerical strings have a numerical value of 0: “the dog” + 3 equals 3 because “the dog” is interpreted as number due to the + sign. “5” + 3 equals 8, because even though “5” is written as a string, the + sign causes it to be interpreted as a number.
Scalar Variables • In Perl, all variables are preceded by a symbol. For scalars (that is, variables with a single value), the sign is “$”. Thus, $cat is a scalar variable that can hold any single value, numerical or string. Later we will see that arrays start with “@”, etc. • Perl variables are named by these rules. • --Only letters, numbers, and underscores are allowed in variable names. • --A letter or underscore must be the first character after the $. • --upper and lower case are considered different from each other. • --variable names can be up to 255 characters long • Basic rule: use meaningful variable names. Don’t use single letter names! Use underscores to separate words within a variable name, or else capitalize the first letter of each word: $the_mangy_dog and $theMangyDog are both good variable names. $r and $themangydog aren’t as good.
Assignment • To assign a value to a variable, use the assignment operator “=“. Thus, $dog = “collie”; assigns the value “collie” to the variable $dog. • Variables can be manipulated with the arithmetic and string operators. Thus, the statements $dog = 3; $big_dog = $dog + 7; result in $big_dog holding the value 10. • Binary assignment operators exist in Perl just like in C. $dog++ means add 1 to $dog. So does ++$dog (which adds one before interpreting the variable), and $dog--. • Also: $dog += 8 adds 8 to $dog, and $dog /= 3 divides $dog by 3. • Also works for concatenation: $dog = 3; $dog .= “red”; causes $dog to equlal the string “3red”.
Print Function • Print is very simple: the word “print” followed by whatever you want printed. If what follows is enclosed in single quotes it is printed as written except for ‘ and \. If in double quotes, escape sequences are interpreted and variables are interpolated. • Thus: $dog = 3; print “$dog”; prints 3. However, $dog = 3; print ‘$dog’; prints $dog. • Or: print “The dog is $dog dog years old”;, which prints “The dog is 3 dog years old”. • You can also print a series of things if they are separated by commas: print “The dog is “, $dog, “dog years old”, “\n”;
Comparison and Logical Operators • Comparison between numbers uses different operators than comparison between strings! • For numerical values: equals is “==“ and not equals is “!=“. Greater than, greater than or equal to, less than, less than or equal to: >, >=, <, <=. • For string values, equals is “eq”, not equals is “ne”. Greater than (gt), greater than or equal to (ge), less than (lt), less than or equal to (le). Note that string comparisons are done character by character, left to right, using the ASCII sequence. Thus, “a” is less than “b” and “a” is greater than “A” (i.e. ASCII 97 vs. ASCII 65). • Logical operators. Negation (not): !. And: &&. Or: ||. • Operator precedence. A table is on page 32, but except for the very well known fact that * and / have precedence over + and -, use parentheses to force precedence the way you want it.
Truth in Perl • These values are “false” in Perl: The value 0, the string “0” (i.e. zero), the empty string “” or ‘’, and the special value “undef” (undefined). • undef is a value a variable has before it has been assigned a value. If you use a variable before assigning it a value, it’s value is “undef”, which is false. • All other scalars are true.
If Statements • To go through a set of alternatives, use if—elsif—else. Note the spelling of “elsif”; it is different from C. • If and elsif have a test clause enclosed in parentheses. The test clause must evaluate to “true” or “false”. • The code to be executed after passing ( or failing) the test clause must be enclosed in curly braces ( { } ), even if it is only a single statement. Note the “preferred” way of using the braces: opening brace on the same line as the test condition, closing brace on a new line, in the same column as the “if”. • For example: if ($dog < 3) { print “Young dog\n”; } elsif ($dog >= 3 && $dog < 10) { print “Middle-aged dog\n”; } else { print “Old dog\n”; }
While Operator • While works just like in C: the test clause is evaluated at the top of the loop, and if it is true, the block of code inside the curly braces is executed. After execution, the test clause is re-evaluated. If false, execution moves to the next statement after the block. • The test clause must evaluate to “true” or “false”, and it must be followed by a block of statements enclosed by curly braces. --There is also a “do-while” construction in Perl as in C. do { } while (logical statement); The loop is executed once, then evaluated. I don’t use this much, but it can come in handy.
Getting User Input • The line input operator is <STDIN>. Perl pauses execution at this operator until you hit “Enter”, at which point it takes whatever you have typed in as the value of <STDIN>. • You then need to assign the input to a variable. $gerbil = <STDIN>; assigns whatever the user has typed to the variable $gerbil. • while ($gerbil = <STDIN>) {print “$gerbil\n”} will run forever. You can stop execution with control-C, which is interpreted as undef, making the test clause false.
Chomp • $gerbil = <STDIN> ; assigns everything typed to $gerbil. This includes the “\n” generated by the Enter key. • To get rid of the newline safely and efficiently, the command “chomp $gerbil;” works well. Only \n at the end is removed; all other characters are unaffected. • Thus a common construction is: while ($gerbil = <STDIN>) { chomp $gerbil; print “You wrote $gerbil, didn’t you?\n”; }