Saturday, January 5, 2013

Learning Perl

Chap 1 Introduction
Welcome to the sixth edition of  Learning Perl, updated for Perl 5.14 and its latest
features.
If you’re looking for the best way to spend your first 30 to 45 hours with the Perl
programming language, you’ve found it.
good for programs from one to 128 lines long, which end up being about 90%
of the programs in use out there.
And when you’re ready to go on, you can get Inter-mediate Perl, which picks up where this book leaves off.
download the code from http://www.learning-perl.com
perl -v
Perl is kind of ugly. This is true. Perl is easy to use, but sometimes hard to learn. Perl is good for quick-and-dirty programs that you whip up in three minutes.
#!/usr/bin/perl
print "Hello, world!\n";

#!/usr/bin/perl
use 5.010;
say "Hello World!";
This program only runs under Perl 5.10 or later.

In Perl, comments run from a pound sign (#) to the end of the line. (There are no “block comments” in Perl. )
Just run your Perl program. The  perlinterpreter compiles and runs your program in
one user step:
$ perl my_program
the compiler is very fast; normally the compilation will be a tiny percentage of the runtime.
The mod_perl extension to the Apache web server or or Perl modules like CGI::Fastcan help you to keep your program in memory between invocations.
#!/usr/bin/perl
@lines = `perldoc -u -f atan2`;
foreach (@lines) {
s/\w<([^>]+)>/\U$1/g;
print;
}
The second line runs an external command, named within  backquotes (` `).

Chap 2 Scalar Data
That last one is a little hard to read. Perl allows you to add underscores for clarity within
integer literals, so you can also write that number with embedded underscores to make
it easier to read:
61_298_040_283_768
Like many other programming languages, Perl allows you to specify numbers in other
ways than base 10 (decimal). Octal (base 8) literals start with a leading 0, hexadecimal
(base 16) literals start with a leading 0x, and binary (base 2) literals start with a leading
0b. Perl also supports a  modulusoperator (%). The operator is represented by the double asterisk, such as 2**3, which is two to the third power, or eight.
If you want to use Unicode literally in your program, you need
to add the utf8pragma:
use utf8;
Also, you should ensure that you save your files with the UTF-8 encoding.
Note that Perl does not interpret the \nwithin a single-quoted string as a newline, but
as the two characters backslash and n. Only when the backslash is followed by another
backslash or a single quote does it have special meaning.
A double-quoted string literalis a sequence of characters, although this time enclosed
in double quotes. But now the  backslashtakes on its full power to specify certain control
characters, or even any character at all through octal and hex representations.
You can concatenate, or join, string values with the  .operator.
"fred" x 3 # is "fredfredfred"
"barney" x (4+1) # is "barney" x 5, or "barneybarneybarneybarneybarney"
5 x 4.8 # is really "5" x 4, which is "5555"
"12" * "3"gives the value 36. Trailing
nonnumber stuff and leading whitespace are discarded, so "12fred34" * " 3"will also
give  36without any complaints.
At the extreme end of this, something that isn’t a
number at all converts to zero. This would happen if you used the string "fred"as a
number.
With Perl 5.6 and later, you can turn on warnings with a pragma
#!/usr/bin/perl
use warnings;
You can use the -woptionon the command line, which turns on warnings everywhere
in your program:
$ perl -w my_program
You can also specify the command-line switches on the shebang line:
#!/usr/bin/perl -w
If you get a warning message you don’t understand, you can get a longer
description of the problem with the diagnostics pragma. The perldiagdocumentation
has both the short warning and the longer diagnostic description, and is the source of
diagnostics’ helpfulness:
#!/usr/bin/perl
use diagnostics;
A further optimization can be had by using one of Perl’s command-line options, -M, to
load the pragma only when needed instead of editing the source code each time to
enable and disable diagnostics:
$ perl -Mdiagnostics ./my_program
Scalar variable names begin with a dollar sign
Using all caps (like $ARGV) generally indicates that there’s something special about that variable.
You can give printa series of values, separated by commas:
print "The answer is ", 6 * 7, ".\n";
To put a real dollar sign into a double-quoted string, precede the dollar sign with a
backslash, which turns off the dollar sign’s special significance:
$fred = 'hello';
print "The name is \$fred.\n"; # prints a dollar sign
Alternatively, you could avoid using double quotes around the problematic part of the
string:
print 'The name is $fred' . "\n"; # so does this
The variable name will be the longest possible variable name that makes sense at that
part of the string.
$what = "brontosaurus steak";
$n = 3;
print "fred ate $n $whats.\n"; # not the steaks, but the value of $whats
print "fred ate $n ${what}s.\n"; # now uses $what

The string value of <STDIN>typically has a newline character on the end of it,
*
so you
could do something like this:
$line = <STDIN>;
if ($line eq "\n") {
print "That was just a blank line!\n";
} else {
print "That line of input was: $line";
}
But in practice, you don’t often want to keep the newline, so you need the  chomp()
operator. if the string ends in a newline character, chomp()removes the newline.
chomp($text = <STDIN>); # Read the text, without the newline character
$text = <STDIN>; # Do the same thing...
chomp($text); # ...but in two steps
$food = <STDIN>;
$betty = chomp $food; # gets the value 1 - but you knew that!
As you see, you may write chomp()with or without the parentheses. This is another
general rule in Perl: except in cases where it changes the meaning to remove them,
parentheses are always optional.
If a line ends with two or more newlines,
chomp()removes only one. If there’s no
newline, it does nothing, and returns zero.

Variables have the special undefvalue before they are first
assigned, which is just Perl’s way of saying

To tell whether a value is undefand not the empty string, use the
defined function, which returns false for undef, and true for everything else:
$madonna = <STDIN>;
if ( defined($madonna) ) {
print "The input was $madonna";
} else {
print "No input available!\n";
}

Of course, the subscript may be any expression that gives a numeric value. If it’s not
an integer already, Perl will automatically truncate it (not round!) to the next lower
integer:
$number = 2.71828;
print $fred[$number – 1]; # Same as printing $fred[1]

$rocks[99] = 'schist';
$end = $#rocks; # 99, which is the last element's index
$rocks[ –1 ] = 'hard rock'; # easier way to do that last example

(1..5) # same as (1, 2, 3, 4, 5)
(1.7..5.7) # same thing; both values are truncated
(5..1) # empty list; .. only counts "uphill"
(0, 2..6, 10, 12) # same as (0, 2, 3, 4, 5, 6, 10, 12)
($m..$n) # range determined by current values of $m and $n
(0..$#rocks) # the indices of the rocks array from the previous section

Of course, a list may have any scalar values, like this typical list of strings:
("fred", "barney", "betty", "wilma", "dino")
qw( fred barney betty wilma dino ) # same as above, but less typing

@rocksis “all of the rocks.”

This works on either side of the assignment operator:
@rocks = qw/ bedrock slate lava /;
@tiny = ( ); # the empty list
@giant = 1..1e5; # a list with 100,000 elements
@stuff = (@giant, undef, @giant); # a list with 200,001 elements
$dino = "granite";
@quarry = (@rocks, "crushed rock", @tiny, $dino);

The popoperator takes the last element off of an array and returns it:
@array = 5..9;
$fred = pop(@array); # $fred gets 9, @array now has (5, 6, 7, 8)
$barney = pop @array; # $barney gets 8, @array now has (5, 6, 7)
pop @array; # @array now has (5, 6). (The 7 is discarded.)

push(@array, 0); # @array now has (5, 6, 0)
push @array, 8; # @array now has (5, 6, 0, 8)
push @array, 1..10; # @array now has those 10 new elements

Similarly, the  unshiftand  shiftoperators perform the corresponding actions on
the “start” of the array (or the “left” side of an array, or the portion with the lowest
subscripts).

@array = qw( pebbles dino fred barney betty );
@removed = splice @array, 2; # remove everything after fred
# @removed is qw(fred barney betty)
# @array is qw(pebbles dino)

@numbers = sort 97..102; # gets 100, 101, 102, 97, 98, 99

use 5.012;
@rocks = qw/ bedrock slate rubble granite /;
while( my( $index, $value ) = each @rocks ) {
say "$index: $value";
}

@people = qw( fred barney betty );
@sorted = sort @people; # list context: barney, betty, fred
$number = 42 + @people; # scalar context: 42 + 3 gives 45

Chapter 4 Subroutine
To define your own subroutine, use the keyword  sub, the name of the subroutine
(without the ampersand), then the block of code in curly braces which makes up the
bodyof the subroutine. Something like this:
sub marine {
$n += 1; # Global variable $n
print "Hello, sailor number $n!\n";
}

You invoke a subroutine from within an expression by using the subroutine name (with
the ampersand):
&marine; # says Hello, sailor number 1!
&marine; # says Hello, sailor number 2!

For example, this subroutine has an addition as the last expression:
sub sum_of_fred_and_barney {
print "Hey, you called the sum_of_fred_and_barney subroutine!\n";
$fred + $barney; # That's the return value
}

To tell Perl that you’re ready to be more restrictive, put the use strictpragma at the
top of your program (or in any block or file where you want to enforce these rules):
use strict; # Enforce some good programming rules
Starting with Perl 5.12, you implicitly use this pragma when you declare a minimum
Perl version:
use 5.012; # loads strict for you



TODO
Input and Output












No comments:

Post a Comment