By Randal L. Schwartz, Erik Olson, Tom Christiansen
Price: $34.95 USD
£24.95 GBP
Cover | Table of Contents | Colophon
http://www.activestate.com. You can also find
the source and binaries for the Perl for Win32 distribution at CPAN.
To use the CPAN archives, visit
http://www.perl.com/CPAN for a mirror site close
to you. The CPAN site will also provide the source distribution for
the UNIX version of Perl and precompiled binaries for other
platforms. If you're absolutely stumped, write
bookquestions@ora.com and say "Where can I
get Perl?!?!"#
!/usr/bin/perl
# is sometimes called sharp, and
! is sometimes called bang. This line normally
won't work for Perl-for-Win32 users,
although it doesn't hurt anything since Perl sees lines
beginning with # as comments.> perl myscript.plx
> myscript.plx
print ("Hello, world!\n");
print starts it off, and in this case has just one
argument, a C-like text string. Within this string, the character
combination \n stands for a newline character,
just as it does in C. The print statement is
terminated by a semicolon (;). As in Pascal or C,
all simple statements in Perl are terminated by a
semicolon.
print function,
which sends any arguments to the standard output. After the program
has completed, the Perl process exits, returning a successful exit
code to the parent process.print and other functions are sometimes called
with parentheses, and sometimes called without them. The rule is
simple: in Perl, parentheses for built-in functions are never
required nor forbidden. Their use can help or hinder clarity, so use
your own judgment.Hello,
world greeting is a touch cold and inflexible. Let's
have the program call you by your name. To do this, we need a place
to hold the name, a way to ask for the name, and a way to get a
response.E notation (that's e or
E). For example:1.25 # about 1 and a quarter
7.25e45 # 7.25 times 10 to the 45th power (a big number)
-6.5e24 # negative 6.5 times 10 to the 24th
# (a "big" negative number)
-12e-24 # negative 12 times 10 to the -24th
# (a very small negative number)
-1.2E-23 # another way to say that
12 15 -2004 3485
hello). Each
character is an 8-bit value from the entire 256-character set
(there's nothing special about the NUL character, as in some
languages).'hello' # five characters: h, e, l, l, o 'don\'t' # five characters: d, o, n, single quote, t '' # the null string (no characters) 'silly\\me' # silly, followed by backslash, followed by me 'hello\n' # hello followed by backslash followed by n 'hello there' # hello, newline, there (11 characters in all)
+ is an operator because it takes two
numbers (the operands, like 5 and 6), and produces a new value (11,
the result).2 + 3 # 2 plus 3, or 5 5.1 - 2.4 # 5.1 minus 2.4, or approximately 2.7 3 * 12 # 3 times 12 = 36 10.2 / 0.3 # 10.2 divided by 0.3, or approximately 34 10 / 3 # always floating point divide, so approximately 3.333333...
2**3, which is 2 to the power of 3, or 8. (If the
result cannot fit into a double-precision floating-point number, such
as a negative number to a noninteger exponent, or a large number to a
large exponent, you'll get a fatal error.)10 % 3 is
the remainder when 10 is divided by 3, which is 1. Both values are
first reduced to their integer values, so 10.5 %
3.2 is computed as 10 % 3.<, <=,
==, >=,
>, and !=. These operators
compare two values numerically, returning a true
or false value. For example,
3 > 2$A is a different variable
from $a. And all of the letters, digits, and
underscores are significant, so:$a_very_long_variable_that_ends_in_1
$a_very_long_variable_that_ends_in_2
$xyz123 is probably not very descriptive, but
$line_length is.$a = 17; # give $a the value of 17 $b = $a + 3; # give $b the current value of $a plus 3 (20) $b = $b * 2; # give $b the value of $b multiplied by 2 (40)
$b variable
twice: once to get its value (on the right side of the
=), and once to define where to put the computed
expression (on the left side of the =). This is
legal, safe, and in fact, rather common. In fact, the practice is so
common that we'll see in a minute that we can write this
expression using a convenient shorthand.$. In batch files, Java, or C, you
don't need the $ at all. If you bounce back
and forth a lot, you'll find yourself typing the wrong things
occasionally. This is expected. (Our solution was to stop writing
batch files and C programs, but that may not work for you.)$a=3 has a
value, just as $a+3 has a value. The value is the
value assigned, so the value of $a=3 is
3. Although this usage may seem odd at first
glance, using an assignment as a value is useful if you wish to
assign an intermediate value in an expression to a variable, or if
you simply wish to copy the same value to more than one variable. For
example:$b = 4 + ($a = 3); # assign 3 to $a, then add 4 to that
# resulting in $b getting 7
$d = ($c = 5); # copy 5 into $c, and then also into $d
$d = $c = 5; # the same thing without parentheses
$a = $a + 5<STDIN> in a
place where a scalar value is expected, Perl reads the next complete
text line from
standard input (up
to the first newline), and uses that string as the value of
<STDIN>. Standard input can mean many
things, but unless you do something odd, it means the command console
that invoked your program. If there's nothing waiting to be
read (typically the case, unless you type ahead a complete line), the
Perl program will stop and wait for you to enter some characters
followed by a newline (return).<STDIN> typically has a
newline
on the end of it. Most often, you'll want to get rid of that
newline right away (there's a big difference between
hello and hello\n). It is at
this point that our friend, the chomp() function,
comes to the rescue. A typical input sequence goes something like
this:
$a = <STDIN>; # get the text chomp($a); # get rid of that pesky newline
chomp($a = <STDIN>);
$a, even after it has been given a value with
<STDIN>. Thus, the
chomp() function is working on
$a. (This is true in general about the assignment
operator—an assignment expression can be used wherever a
variable is needed, and the actions refer to the variable on the left
side of the equal sign.)<STDIN>. How do we
get things out? With the
print()
function. This function takes the values within its parentheses and
puts them out without any embellishment onto
standard output.
Once again, unless you've done something odd, this will be your
command console. For example:print("hello world\n"); # say hello world, followed by newline
print "hello world\n"; # same thing
print() without parentheses. In fact, many of the
operators that look like functions also have a syntactic form that
works without the parentheses. Whether or not to use the parentheses
is mostly a matter of style and typing agility, although there are a
few cases where you'll need the parentheses to remove
ambiguity.print a list of values, in
Section 6.3.1 in Chapter 6,
but we haven't talked about lists yet, so we'll put that
discussion off until later.undef value before they are first assigned. This
value looks like a zero when used as a number, or the zero-length
empty string when used as a string. You will get a warning when
running under Perl's -w switch, though,
which is a good way to catch programming errors.undef
when the arguments are out of range or don't make sense. If you
don't do anything special, you'll get a zero or a null
string without major consequences. In practice, this scenario is
hardly a problem.undef
under certain circumstances is
<STDIN>
. Normally, this returns
the next line that was read; however, if there are no more lines to
read, (such as when you type CTRL-Z at the terminal, or when a file
has no more data),
<STDIN>
returns undef as a
value. In Chapter 6, we'll see how to test
for this and take special action when there is no more data available
to read.12.5. The circumference is 2π times the radius, or about 2 times 3.141592654.x operator.)(1,2,3) # array of three values 1, 2, and 3
("fred",4.5) # two values, "fred" and 4.5
($a, 17) # two values: the current value of $a, and 17 ($b+$c,$d+$e) # two values
() # the empty list (zero elements)
(1..5) # same as (1, 2, 3, 4, 5) (1.2..5.2) # same as (1, 2, 3, 4, 5) (2..6,10,12) # same as (2,3,4,5,6,10,12) ($a..$b) # range determined by current values of $a and $b
(1,2,3) # array of three values 1, 2, and 3
("fred",4.5) # two values, "fred" and 4.5
($a, 17) # two values: the current value of $a, and 17 ($b+$c,$d+$e) # two values
() # the empty list (zero elements)
(1..5) # same as (1, 2, 3, 4, 5) (1.2..5.2) # same as (1, 2, 3, 4, 5) (2..6,10,12) # same as (2,3,4,5,6,10,12) ($a..$b) # range determined by current values of $a and $b
(1.3..6.1) # same as (1, 2, 3, 4, 5)
@a = ("fred","barney","betty","wilma"); # ugh!
@a = qw(fred barney betty wilma); # better! @a = qw( fred barney betty wilma ); # same thing
@)
rather than a dollar sign ($). For example:@fred # the array variable @fred @A_Very_Long_Array_Variable_Name @A_Very_Long_Array_Variable_Name_that_is_different
@fred is unrelated to
the scalar variable $fred. Perl maintains separate
namespaces for
different types of things.(), the
empty list.@fred = (1,2,3); # The fred array gets a three-element literal @barney = @fred; # now that is copied to @barney
@huh = 1; # 1 is promoted to the list (1) automatically
# that is, @huh now is (1)
@fred = qw(one two);
@barney = (4,5,@fred,6,7); # @barney becomes
# (4,5,"one","two",6,7)
@barney = (8,@barney); # puts 8 in front of @barney
@barney = (@barney,"last"); # and a "last" at the end
# @barney is now (8,4,5,"one","two",6,7,"last")
($a,$b,$c) = (1,2,3); # give 1 to $a, 2 to $b, 3 to $c
($a,$b) = ($b,$a); # swap $a and $b
($d,@fred) = ($a,$b,$c); # give $a to $d, and ($b,$c) to @fred
($e,@fred) = @fred; # remove the first element of @fred to $e
# this makes @fred = ($c) and $e = $b@fred
returns the contents of the @fred array in a list
context, but the length of the same array in a scalar context. These
subtleties are mentioned when each operator and function is
described.<STDIN>
. As described earlier,
<STDIN> returns the next line of input in a
scalar context. However, in a list context, it returns
all of the remaining lines up to the
end-of-file. Each line is returned as a separate element of the list.
For example:@a = <STDIN>; # read standard input in a list context
@fred = ("hello","dolly");
$y = 2;
$x = "This is $fred[1]'s place"; # "This is dolly's place"
$x = "This is $fred[$y-1]'s place"; # same thing
@fred = ("hello","dolly"); # give value to @fred for testing
$fred = "right";
# we are trying to say "this is right[1]"
$x = "this is $fred[1]"; # wrong, gives "this is dolly"
$x = "this is ${fred}[1]"; # right (protected by braces)
$x = "this is $fred"."[1]"; # right (different string)
$x = "this is $fred\[1]"; # right (backslash hides it)
@ character). In this case, the elements are
interpolated in sequence with a
space character between
them, as in:@fred = ("a","bb","ccc",1,2,3);
$all = "Now for @fred here!";
# $all gets "Now for a bb ccc 1 2 3 here!"
@fred = ("a","bb","ccc",1,2,3);
$all = "Now for @fred[2,3] here!";
# $all gets "Now for ccc 1 here!"
$all = "Now for @fred[@fred[4,5]] here!"; # same thing
@somearray, putsrand;
rand(@somearray)
@somearray.