Scalar Variables


The simplest type of variable in Perl is called a scalar variable. These hold a single value, either a number or a string. A scalar variable name always starts with a $, as in

 $pi = 3.14159; $name = "Hamlet\n"; print $name;

Note that this is different from shell scripting, in which you only need the $ when you want the value of the variable. Variable names are case sensitive, as is the language in general.

As in shell scripting, you do not need to explicitly declare variables in Perl. In addition, Perl will interpret whether a variable contains a string or a number according to the context. For example, the following program will print the number 54:

 $string = "27"; $product = $string * 2; print "$product \n";

The default value for a variable is 0 (for a number) or “” (for a string). You can take advantage of this by using variables without first initializing them, as in

 $x = $x + 1;

If this is the first time $x has been used, it will start with the value 0. This line will add 1 to that value and assign the result back to $x. If you print $x, you will find that it now equals 1.

Working with Numbers

A shorter way to write the previous example is

 $x += 1;                  # add 1 to the current value of $x

or even

 $x++;                    # increment $x

C programmers will recognize these handy shortcuts. This works with subtraction, too:

 $posX = 7.5; $posY = 10; $posX −= $posY;            # subtract $posY from $posX, so that $posX equals −2.5 $posY--;                   # $posY is now 9

In addition to += and =, Perl supports *= (for multiplication) and /= (for division). Exponentiation is done with **, as in

 $x = 2**3;                # $x is now 8 $x ** = 2;               # $x equals $x ** 2, or 8 ** 2, which is 64

and modular division is done with %.

The function int converts a number to an integer. Other math functions include sqrt (square root), log (natural logarithm), exp (e to a power), and sin (sine of a number). For example,

 $roll = int (rand(6))+1;      # random integer from 1 to 6 print exp 1;                  # prints the value of e, approx 2.718281828 $pi = 4 * at an2(1, 1);       # at an2 ($x, $y) returns the arctan of $x/$y

Entering Numbers

There are many ways to enter numbers in Perl, including scientific notation. All of the following declarations are equivalent:

 $num = 156.451; $num = 1.56451e2;         # 1.56451 * (10 ** 2) $num = 1.56451E2;         # same as previous statement $num = 156451e-3;         # 156451 * (10 ** −3)

Perl can also interpret numbers in hex, octal, or binary. See http://perldoc.perl.org/perldata.html for details.

Perl performs all internal arithmetic operations with double-precision floating-point numbers. This means that you can mix floating-point values with integers in your calculations.

Working with Strings

String manipulation is one of Perl’s greatest strengths. This section introduces some of the simplest and most common string operations. More powerful tools for working with strings are discussed in the section “Regular Expressions” later in this chapter.

The . (dot) operator concatenates strings. This can be used for assignment

 $concat = $str1 . $str2;

or when printing, as in

 $name1 = "Rosencrantz"; $name2 = "Guildenstern"; print $name1 . "and " . $name2 . "\n";

which prints Rosencrantz and Guildenstern.

Variables can be included in a string by enclosing the whole string in double quotes. This example is a more compact way of writing the preceding print statement:

 print "$name1 and $name2\n";

Here the values of $name1 and $name2 are substituted into the line of text before it is printed. The \n in this example is an escape sequence (for the newline character) that is interpreted before printing as well.

Another example of an escape sequence is \t, which stands for the tab character. Other escape sequences that are interpreted in double-quoted strings include \u and \l, which convert the next character to upper- or lowercase, and \U and \L, which convert all of the following characters to upper- or lowercase. For example,

 $ perl -e 'print "\U$name1 \L$name2\n"' ROSENCRANTZ guildenstern

To turn off variable substitution, use single quotes. The line

 print '$name1 and $name2\n';

will print, literally, $name1 and $name2\n, without a newline at the end. Alternatively, you could use a \ (backslash) to quote the special characters $ and \ itself.

The x operator is the string repetition operator. For example,

 print '*' x 80;                          # repeat the character '*' 80 times

prints out a row of 80 *s.

As its name implies, the length function returns the length of a string-that is, the number of characters in a given string:

 $length = length ("Words, words, words.\n") ;

In this example, $length is 21, which includes the newline at the end as one character.

The index and rindex functions return the position of the first and last occurrences, respectively, of a substring in a string. The position in the string is counted starting from 0 for the first character. In this example,

 $posFirst = index ("To be, or not to be", "be"); $posLast = rindex ("To be, or not to be", "be");

$posFirst is three and $posLast is 17.

These two functions are commonly combined with a third, called substr. This function can be used to get a substring from a string, or to insert a new substring. The first argument is the current string. The next argument is the position from which to start, and the optional third argument is the length of the substring (if omitted, substr will continue to the end of the original string). When substr is used for inserting, a fourth argument is included, with the replacement substring. In this case, the function modifies the original string, rather than returning the new string.

 $name = "Laurence Kerr Olivier"; # Get the substring that starts at 0 and stops before the first space: $firstname = substr($name, 0, index ($name,' ')) ;    # $firstname = "Laurence" # Substring that starts after the last space and continues to the end of $name: $lastname = substr($name, rindex ($name, ' ')+1) ;    # $lastname = "Olivier" substr($name, 9, 5, "");

In the last line of this example, the function substr starts at index 9 and replaces five characters (“Kerr ”) with the empty string-that is, the five characters are removed. If you were to print the variable $name at this point, you would see “Laurence Olivier”.

Here’s another way to modifying an existing string with substr, by assigning the new substring to the result of the function:

 $path = "/usr/bin/perl"; # Replace the characters after the last / with "tclsh": substr($path, rindex ($path, "/") + 1) = "tclsh";    # $path = "/usr/bin/tclsh" # Insert the string "local/" at index 5 in $path: substr($path, 5, 0) = "local/";                      # "/usr/local/bin/tclsh"

Perl includes many more ways to manipulate strings, such as the reverse function, which reverses the order of characters in a string, or the sprintf function, which can be used to format strings. See the sources listed at the end of this chapter for further details about these functions and other useful string operations.

Variable Scope

By default, Perl variables are global, meaning that they can be accessed from any part of the script, including from inside a procedure. This can be a bad thing, especially if you reuse common variable names like $i or $x. You can declare local variables with the keyword my, as in

 my $pi = 3.14159;

It is generally considered good practice to do this for any variable that you don’t specifically need to use globally If you add the line

 use strict;

to the top of your script, perl will enforce the use of my to declare variables, and generate an error if you forget to do so.

Reading in Variables from Standard Input

To read input from the keyboard (actually, from standard input), just use <STDIN> where you want to get the input, as in

 print "Please enter your name: "; my $name = <STDIN>; print "Hello, $name.\n";

When you run this script, the output might look something like

  Please enter your name: Ophelia Hello, Ophelia 

Note that the period ended up on its own line. That’s because when you typed in the name Ophelia and pressed ENTER, <STDIN> included the newline at the end of your string, so the print statement actually printed Hello, Ophelia\n.\n. To fix this, use the command chomp to remove a newline from the end of a string, as shown:

 my $name = <STDIN>; chomp($name);

If for some reason there is no newline at the end, chomp will do nothing.

You will almost always want to chomp data as you read it in. Because chomp is used so frequently, the following shortcut is common:

 chomp(my $name = <STDIN>);




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net