Friday, March 1, 2013

Learning Perl


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.
Rather than copying by hand, however, we
encourage you to download the code from http://www.learning-perl.com.

Perl is easy to use, but sometimes hard to learn. Like any language, Perl can be “write-only”—it’s possible to write programs that are
impossible to read.
Most statements are an expression followed by a semicolon;

perl hello.pl

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.

If you want to use Unicode literally in your program, you need
to add the utf8 pragma:§
use utf8;

\x{2744} Any hex Unicode code point (here, U+2744 = snowflake)
\cC A “control” character (here, Ctrl-C)
\l Lowercase next letter
\L Lowercase all following letters until \E
\u Uppercase next letter
\U Uppercase all following letters until \E
\Q Quote nonword characters by adding a backslash until \E

"hello" . ' ' . "world" # same as 'hello world'
"barney" x (4+1) # is "barney" x 5, or "barneybarneybarneybarneybarney"

Trailing
nonnumber stuff and leading whitespace are discarded, so "12fred34" * " 3" will also
give 36 without 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.

The trick of using a leading zero to mean an octal value works for literals, but never for
automatic conversion, which is always base-10:#
0377 # that's octal for 255 decimal
'0377' # that's 377 decimal

you can turn on warnings with a pragma
#!/usr/bin/perl
use warnings;
You can use the -w option on the command line, which turns on warnings everywhere
in your program:§
$ perl -w my_program

If you get a warning message you don’t understand, you can get a longer
description of the problem with the diagnostics pragma.
#!/usr/bin/perl
use diagnostics;

Scalar variable names begin
with a dollar sign

$str = $str . " "; # append a space to $str
$str .= " "; # same thing with assignment operator

You can give print a series of values, separated by commas:
print "The answer is ", 6 * 7, ".\n";

$fred = 'hello';
print "The name is \$fred.\n"; # prints a dollar sign

$alpha = chr( hex('03B1') );
$omega = chr( 0x03C9 );
You can go the other way with the ord() function, which turns a character into its code
point.
That might be more work than interpolating them directly by putting the hexadecimal
representation in \x{}:
"\x{03B1}\x{03C9}"

if ($name gt 'fred') {
print "'$name' comes after 'fred' in sorted order.\n";
} else {
print "'$name' does not come after 'fred'.\n";
print "Maybe it's the same string, in fact.\n";
}

$is_bigger = $name gt 'fred';
if ($is_bigger) { ... }

Perl doesn’t have a
separate Boolean datatype, like some languages have. Instead, it uses a few simple
rules:‡
• If the value is a number, 0 means false; all other numbers mean true.
• Otherwise, if the value is a string, the empty string ('') means false; all other strings
mean true.
• Otherwise (that is, if the value is another kind of scalar than a number or a string),
convert it to a number or a string and try again.§
the string
'0' is the only non-empty string that is false.

$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.

chomp($text = <STDIN>); # Read the text, without the newline character
$text = <STDIN>; # Do the same thing...
chomp($text); # ...but in two steps

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.

To tell whether a value is undef and 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";
}

A list is an ordered collection of scalars. An array is a variable that contains a list. The list is the data
and the array is the variable that stores the data.

For the array of
rocks, the last element index is $#rocks
That’s not the same as the number of elements,
though, because there’s an element number zero

If you have three elements in
the array, the valid negative indices are –1 (the last element), –2 (the middle element),
and –3 (the first element).

a list may have any scalar values, like this typical list of strings:
("fred", "barney", "betty", "wilma", "dino")
The qw shortcut makes it easy to generate them without typing a lot
of extra quote marks:
qw( fred barney betty wilma dino ) # same as above, but less typing

In much the same way as you can assign scalar values to variables, you can assign list
values to variables:
($fred, $barney, $dino) = ("flintstone", "rubble", undef);

Just use the
at sign (@) before the name of the array (and no index brackets after it) to refer to the
entire array at once. You can read this as “all of the,” so @rocks is “all of the rocks.”

When an array is copied to another array, it’s still a list assignment. The lists are simply
stored in arrays. For example:
@copy = @quarry; # copy a list from one array to another

The pop operator 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, 8; # @array now has (5, 6, 0, 8)
push @array, 1..10; # @array now has those 10 new elements

Similarly, the unshift and shift operators perform the corresponding actions on
the “start” of the array

The push-pop and shift-unshift operators work with the ends of the array, but what if
you need to remove or add elements to the middle? That’s where the splice operator
comes in. It takes up to four arguments, two of which are optional. The first argument
is always the array and the second argument is the position where you want to start. If
you only use those two arguments, Perl removes all of the elements from your starting
position to the end and returns them to you

$email = "fred@bedrock.edu"; # WRONG! Tries to interpolate @bedrock
$email = "fred\@bedrock.edu"; # Correct
$email = 'fred@bedrock.edu'; # Another way to do that

foreach (1..10) { # Uses $_ by default
print "I can count to $_!\n";
}

reverse @fred; # WRONG - doesn't change @fred
@fred = reverse @fred; # that's better

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

Scalar and List Context
@people = qw( fred barney betty );
@sorted = sort @people; # list context: barney, betty, fred
$number = 42 + @people; # scalar context: 42 + 3 gives 45
Even ordinary assignment (to a scalar or a list) causes different contexts:
@list = @people; # a list of three people
$n = @people; # the number 3

@backwards = reverse qw/ yabba dabba doo /;
# gives doo, dabba, yabba
$backwards = reverse qw/ yabba dabba doo /;
# gives oodabbadabbay

@betty = ( ); # A correct way to empty an array

No comments:

Post a Comment