Perl Notes (I)

Source: Internet
Author: User
Tags chop perl interpreter scalar stdin

Part I Programming Perl 1 Perl Data Types 1.1 Funny Characters

is
Type Character Examplea name for:
Scalar $ $cents An individual value (number or string)
Array @ @large A list of values, keyed by number
Hash % %interest A Group of values, keyed by string
Subroutine & &how A callable chunk of Perl code
Typeglob * *struck Everything named struck
1.2 singularities Strings and numbers are singular pieces of data, while lists of Strings or numbers are. Scalar variables can be assigned any form of Scalar value:integers, floating-point numbers, strings, and even esoteric th Ings like references to the other variables, or to objects.

As in the Unix shell, your can use different quoting mechanisms to make different kinds of values. Double quotation marks (double quotes) do variable interpolation and backslash interpolation (such as turning/n into NE Wline) while the single quotes suppress interpolation. and Backquotes (the ones leaning to the "left") would execute a external program and return the output of the "program", so Can capture it as a single string containing all the lines of output.

$answer = 42; # an integer
$pi = 3.14159265, # a "real" number
$avocados = 6.02e23; # scientific notation
$pet = "Camel"; string
$sign = "I Love Me $pet"; # string with interpolation
$cost = ' It costs $ '; # string without Interpolati On
$thence = $whence; # Another variable ' s value
$salsa = $moles * $avocados; # a gastrochemical expression
$e XIT = System ("VI $file"); # Numeric status of a command
$CWD = ' pwd '; # string output from a command
And while we haven ' t covered fancy values yet, we should point out of that scalars could also hold references to other data str Uctures, including subroutines and objects.
$ary =/@myarray; # Reference to a named array
$hsh =/%myhash: # Reference to a named hash
$sub =/&mysub; # Reference to a Nam Ed subroutine

$ary = [1,2,3,4,5]; # Reference to a unnamed array
$hsh = {Na =>, Cl =>}; # Reference T o A unnamed hash
$sub = sub {print $state}; # Reference to a unnamed subroutine

$fido = new Camel ' Amelia '; Reference to an Object
Following the principle of least surprise, the variable is created with a null value, either "" "or 0. Depending on where to use them, variables to be interpreted automatically as strings, as numbers, or as "true" and "Fal Se "values" (commonly called Boolean values). Perl would automatically convert the data into the form required by the current context, within reason. For example, suppose your said this:
$camels = ' 123 ';
Print $camels + 1, "/n";
The original value of $camels is a string, but it are converted to a number to add 1 to it, and then converted back to a String to is printed out as 124.

Similarly, a reference behaves as a reference when your give it a "dereference" context, but otherwise the like a simple s Calar value. For example, we might say:

$fido = new Camel "Amelia";
if (not $fido) {die "Dead Camel";}
$fido->saddle ();
1.3 pluralities Perl has two types of multivalued variables:arrays and hashes. 1.3.1 Array An array is a ordered list of scalars, accessed[6] by the scalar ' s position in the list. To assign a list value to a array, and you are simply group the values together (with a set of parentheses):
@home = ("couch", "chair", "table", "stove");
Conversely, if you are @home in a list context, such as on the right side of a list assignment, and you are back out the same The list is in. So your could set four scalar variables from the "array like this:
($potato, $lift, $tennis, $pipe) = @home;
These are called list assignments. They logically happen in parallel. Can swap two variables by saying:
($alpha, $omega) = ($omega, $alpha);
Arrays are zero-based. Array subscripts are enclosed in square brackets [like this], so if you are want to select a individual array element, you wo Uld refer to it as $home [n].
Since arrays are ordered, you can do various useful to operations on them, such as the stack operations push and pop. Perl regards the Endof your array as the top of a stack.
1.3.2 Hash A Hash is a unordered set of scalars, accessed by some string value this is associated with each scalar.  For this reason hashes are often called associative. A Hash has no beginning or end. Since the keys to a hash are not automatically implied by their position, you must supply the key as as as the value whe n Populating a hash.

Suppose you wanted to translate abbreviated day names to the corresponding full names. You could write the following list assignment:

%longday = ("Sun", "Sunday", "Mon", "Monday", "Tue", "Tuesday",
 "Wed", "Wednesday", "Thu", "Thursday", "Fri",
 "Fr Iday "," Sat "," Saturday ");
But that ' s rather difficult to read and so Perl provides the=>(equals sign, Greater-than sign) sequence as a alternative separator to the comma. Using this syntactic sugar (and some creative formatting), it are much easier to, which strings are the keys and which s Trings are the associated values.
%longday = (
 "Sun" => "Sunday", "
 Mon" => "Monday",
 "Tue" => "Tuesday",
 "Wed" => "Wednesday", "
 Thu" => "Thursday",
 "Fri" => "Friday",
 "Sat" => "Saturday",
);
You can select a individual hash element by enclosing the key in braces (those fancy brackets also known as "Curlies"). For example, if you want the value associated with Wed in the hash of above, you would use $longday {"Wed"}. Note again this you are dealing with a scalar value, so your use $ on the front, not%, which would-indicate the entire h Ash.

Linguistically, the relationship encoded in a hash are genitive or possessive, like the word "of" in Chinese, or like "' s". The wife of Adam is Eve, so we write:

$wife {"Adam"} = "Eve";
1.3.3 Complexities Perl lets you manipulate simple scalar references which happen to refer to complicated arrays and hashes. To extend we are previous example, suppose we want to switch from talking about Adam's wife to Jacob's wife. Now, as it happens, Jacob had four wives. (Don ' t try this in home.) In trying to represent this in Perl, we find ourselves in the odd situation where we'd like to pretend that Jacob ' s four W Ives were really one wife. (Don ' t try this in home, either.) You might would like to could write it like this:
$wife {"Jacob"} = ("Leah", "Rachel", "Bilhah", "Zilpah"); # wrong
But that wouldn ' t does what you want because even the parentheses and commas are powerful to enough a list into a turn Ar in Perl. (parentheses are used for syntactic grouping, and commas for syntactic separation.) Rather, you are need to tell Perl explicitly so you want to pretend that a-list is a scalar. It turns out this square brackets are powerful enough to do:
$wife {"Jacob"} = ["Leah", "Rachel", "Bilhah", "Zilpah"]; # OK
That is statement creates an unnamed array and puts a reference to it into the hash element $wife {"Jacob"}. Suppose we wanted to list not only Jacob's wives but all the sons of each of his wives. In this case we are want to treat a hash as a scalar. We can use the braces for that. (Inside each hash value we'll use the square brackets to represent arrays, just as we did earlier. But now we have a hash of array in a.
$kids _of_wife{"Jacob"} = {"
 Leah" => ["Reuben", "Simeon", "Levi", "Judah", "Issachar", "Zebulun"],
 "Rachel" = > ["Joseph", "Benjamin"],
 "Bilhah" => ["Dan", "Naphtali"],
 "Zilpah" => ["Gad", "Asher"],
};
That would is more or less equivalent to saying:
$kids _of_wife{"Jacob"} {"Leah"}[0] = "Reuben";
$kids _of_wife{"Jacob"} {"Leah"}[1] = "Simeon";
$kids _of_wife{"Jacob"} {"Leah"}[2] = "Levi";
$kids _of_wife{"Jacob"} {"Leah"}[3] = "Judah";
$kids _of_wife{"Jacob"} {"Leah"}[4] = "Issachar";
$kids _of_wife{"Jacob"} {"Leah"}[5] = "Zebulun";
$kids _of_wife{"Jacob"} {"Rachel"}[0] = "Joseph";
$kids _of_wife{"Jacob"} {"Rachel"}[1] = "Benjamin";
$kids _of_wife{"Jacob"} {"Bilhah"}[0] = "Dan";
$kids _of_wife{"Jacob"} {"Bilhah"}[1] = "Naphtali";
$kids _of_wife{"Jacob"} {"Zilpah"}[0] = "Gad";
$kids _of_wife{"Jacob"} {"Zilpah"}[1] = "Asher";
1.3.4 simplicities

Perl also has several ways of topicalizing. One important topicalizer is the package declaration. Suppose you want to talk about camels in Perl. You ' d likely start off your Camel module by saying:

Package Camel;
Perl would assume from this point to the unspecified verbs or nouns are about camels. It does this by automatically prefixing any global name with the module name "Camel::".

When your say package Camel, you ' re starting a new package. But Sometimes you just want to borrow the nouns and verbs of the existing. Perl lets you, declaration, which is only borrows verbs from another package, but also and checks Module you are loaded in from disk. In fact, your must say something like:

Use Camel;
Before you say:
$fido = new Camel "Amelia";

In fact, some of the built-in modules don ' t actually introduce verbs on all, but simply warp the Perl language in various Useful ways. These special modules we call pragmas. For instance, you ' ll often to use the pragma strict of people use:

Use strict;
1.4 Verbs Many of the verbs in Perl are commands:they tell the Perl interpreter to did Something. a statement with A Verb is generally purely imperative and evaluated to entirely for its side. (We sometimes call this verbs  procedures, especially when they ' re user-defined.) The other verbs translate their input parameters into return values, just as a recipe tells you are to turn raw ingredients in to something (hopefully) edible. We tend to call these verbs  functions. Verbs are also sometimes called operators (when built-in), or subroutines. user-defined, Perl  historically Uired to put a ampersand character (&) on any calls to user-defined subroutines (see  $fido = &fetch ();  earlier). But with Perl version 5, the ampersand became optional, so this user-defined verbs can now is called with the same syntax As built-in verbs ($fido = fetch ();).  we still use the ampersand when talking about the  name of the Routi NE, SUch as when we take a reference to it ($fetcher =/&fetch;). 1.5 filehandles A filehandle is just a name you give to a file, device, socket, or pipe to help you remember which one you ' re talking Abou T, and to hide some of the complexities of buffering and such. (Internally, filehandles are similar to streams from a language like C + + or I/O channels from BASIC.) Create a filehandle and attach it to a file by using  Open. TheOpenfunction takes at least two parameters:the filehandle and filename for your want to associate it with. Perl also gives you some predefined (and preopened) filehandles.STDINIs your program ' s normal input channel whileSTDOUTIs your program ' s normal output channel. andSTDERRis a additional output channel that allows your program to do snide remarks off to the side while it transforms (or att Empts to transform) your input into your output.
Open (SESAME, "filename") # read from existing file
open (SESAME, "<filename") # (same thing, explicitly)
open (S Esame, ">filename") # Create file and write to it
open (SESAME, ">>filename") # Append to existing file
op En (SESAME, "| Output-pipe-command ") # Set up a output filter
open (SESAME," Input-pipe-command | ") # set up a input filter
As you can, the name of the pick for the filehandle is arbitrary. Once opened, the FileHandle SESAME can be used to access the file or pipe until it are explicitly (with, for you closed D it,Close (SESAME)), or until the filehandle is attached to another file by a subsequent open on the same filehandle.  Once ' ve opened a filehandle for input, can read a line using the line reading operator, <. The angle operator encloses the filehandle (<SESAME>) you want to read lines from. The empty angle operator, <>, would read lines from all the files specified on the command line, or STDIN, if non e were specified.

An example using the STDIN filehandle to read a answer supplied by the user would look something like this:

Print STDOUT "Enter a number:"; # Ask for a number
$number = <STDIN>; input
The number print STDOUT ' The number is $number./n '; # print th E number

If You try the previous example, your may notice this you get a extra blank line. This happens because the line-reading operation does not automatically remove the newline from your input line (your input Would is, for example, "9/n"). For those times if you did want to remove the newline, Perl provides the  Chop  and chomp  functions. chop will indiscriminately remove (and return), the last character of the String, While chomp will only remove the ' end of the ' record marker (Generally, ' n ') and return the number of charact ERs so removed. you ' ll often to the idiom for inputting a single:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.