Perl Summary from Camel Book

  1. first line:      #!/usr/bin/perl
  2. automatically, find the path of perl using env supported by unix

fist line: #!/usr/bin/env perl

(Non-unix system, the first line usually be: #!perl)

  1. chmod a+x program // using in shell a+x = 755
  2. print “ …\n” ;==   say “…..”-----Not necessary to input “\n”  compared with print, otherwise same function
  3. The end of one line is denoted by semicolon (;)
  4. ` ….. `   ---run the outer function and return the result

@lines= `perldoc –u –f atan2` ---result return to array “lines”

Ps: ` is reverse of ‘; it’s located in front of key for number “1”

foreach(@lines) { xxxx; print; }

  1. Division always gives the exact result;

Modulus operation first find the integer (deleting the following fractional part), then do the modulus operation

Exponentiation: 2**3 = 2^3

  1. Single quoted string: anything is itself. (for representation of ‘ , using \, special case is \ is the last char in the string, we use \\ for this special and delete ambiguity)
  2. Double quoted string: more powerful, we can use variables, expressions
  3. Controlling :

\l             next becomes lower

\L            The following becomes lower until encounters \E

\u            next one becomes upper

\U           The following becomes upper until encounters \E

\Q           The following until encounters \E, non-word char add \ before it

  1. String operation

Concatenation:  .                “cat”.”pig”---à”catpig”

String Repetition: “..” x N                  “ab”x2 -à “abab”  (if N is not integer, deleting the following digits, like 4.8 à4)

Automatically, transform between string and number, mainly according to the operation needed

 

  1. Inner build the “warning” function
    1. #!/usr/bin/perl –w
    2. perl –w program
    3. #!/usr/bin/perl

use warnings;

  1. use diagnostics;  giving the detailed explanation for the mistakes; perl –Mdiagnostics program;
  2. Scalar variable: headed with $, case sensitive

variable name with all uppercase: usually represents some special variable.

 

  • operations: +, +=, *. *=, **=

print: print some non-formatted scalar variables/literals; can also print many separated with comma “,”; print “a is: “, 6*7, “\n”;

 

print $a == print “$a”

For variable names, some time to avoid ambiguity, we use curly brace {}

print “$whats” -àprint”${what}s”   where $what is variable

 

 

special: ** right preferred 2**3**4= 2**(3**4)

  1. Number comparison: same with C++

String comparison: lt, gt, eq le, ge, ne (The order of Uppercase is before Lowercase)

 

  1. if(…) {…} else {….}

No Boolean variable in Perl; “0” =0;

To get reverse Boolean value: !$express

  1. Line input for the standard input (<STDIN>):

$line=<STDIN>

  1. chomp: remove the “line break”—“\n” for end of the string; change occurs in the original string

$line=<STDIN>;
chomp($line);

==

chomp($line=<STDIN>

We can also ignore the brace,
if it doesn’t change the original meaning.

If the ending of a string have
two or more “line break”, chomp can only drop one

 

  1. while(…) {….}
  2. “undef” type: before assignment, the type of variable is undef, for
    number 0, for string null. But undef is neither number nor string.
  3. When reading end-of-file, <STDIN> will return undef; To decide a
    string is undef rather than null, we use “defined” function.

$line=<STDIN>;

if(defined($line)) {} else {}.

 

~~~ Chapter 3~~

  1. list for set of data; array for set of variables;

Index comes from 0
increasingly; No limit for the size of list/array

Namespace for array and scalar
variable is separated.

When using expression as index
and it’s not integer, just ignore the fractional part and make it a integer.

$arr[0], $arr[1],….

  1. Index for the last element in array “arr”

         $#arr

last element arr[$#arr]

 

Negative index: -1 --- The last
element

arr[-1]  last one

arr[-2]  last second one

 

  1. list: (a, b, c)

.. : Range Operator;
(1..100)  1,2,3,4,100

(5..1): null list, it can only
increase by using ...

 

  1. qw: quoted word/ quoted by whitespace++++++ build easy word list

                e.g.
qw(a b c)    --à (“a”, “b”, “c”)

                qw
##   !! <> []{}() //

        anything in qw is set as the single
quoted string

  1. Assignment for list: ($a, $b, $c) = (x, y, z)

($a, $b) = ($b, $a) // exchange
the value, it first builds the list in the right, and then assign it the list
in the left.

Reference to the array, just
add @ before the name of array

@arr=qw\a b c\;

($calar scalar; @rray
array—explanation for $ @ representing list and array)

@arr=(@a1, “aa”, “bb”,undef); #
unfold a1 to element and add to arr

@arr=@a1; // array assignment

  1. pop, push for array

Pop and push works on the right
of the array;

pop delete the last one and
return this value

$a1=pop(@arr); // sometimes, we
just use “pop @arr;”—void context, there is no place to hold the returned value.

 

push: push one or a list of
elements to the end of array

push(@arr, 3)

push(@arr, qw\a, b, c\)

push(@arr, @other)

  1. shift, unshift for array

shift and unshift works on the
left(lower index) of the array

shift: delete the first element
from array and return it

 $a1= shift(@arr)

shift @arr;

 

unshift insert in the first

unshift(@arr, 3);

 

Other: we can also use print
“xxxxx @arr xxdf “; //@arr will show one by one

  1. To avoid ambiguity between array and scalar variable

@fred=qw(a, b, c);

$fred=r;

print “$fred[2]” ; // c

print “${fred}[2]”;// r[2]

print “$fred\[2]”; r]2],   \ using to avoid ambiguity

  1. foreach $x qw(a b c) {}
  2. foreach $x @arr {}

control variable $x, is not the
copy of the element of @arr, it’s reference to @each element of @arr, the
modification to $x will lead to the modification of @arr;

Also, the control/loop variable
will not change the value of control variable $x

 

If one ignores to specify the
control variable, then the default control variable is $_

  1. reverse: return the reverse list for a
    given list

@a1=reverse(@arr)

This is reference by value and
will not change the values of original array @arr

  1. sort: by ASCII coding, Uppercase
    smaller than Lowercase, Number smaller than character (upper and lower case)

reference by value and will not
change parameter

@arr= sort @arr;

  1. Scalar context and list context according to the context.

In scalar
context, @arr returns the number of element in @arr.

 

  1. Scalar
    context and list context

The explanation of scalar or array or list depends on
the context

$a1= @arr;   $a1
is the concatenate of all element in @arr

 

Clear the array: @arr=();

 

Force type transformation: scalar @arr;
---return the number of elements in @arr

 

<STDIN>

Scalar context: return the next row of input data

List context: return all the remaining rows until end
of file, and each row will become elements in list. @lines=<STDIN>

End of file: Ctrl+D (Linux and Mac OS X), Ctrl+Z(Windows and Dos)

 

chomp(@lines=<STDIN>);

~~~`Chapter 4 Subroutine, subprogram

  1. Define
    sub program: sub abc{ }

It can be placed any place in the program. Sub program
has independent namespace. (Program with same name, the later one will be
hidden by the use of the first one.)

  1. Call
    sub program using the &

Each sub program will have a return
value, which is the result of the last operation.

#: as the beginning of comment.

 

There can be parameters in the
subroutines. Parameters are stored in array _, denoting by @_: element of it is: $_[0],
$_[1],…

@_ is the private variable for the subroutine.

All variables in Perl is global. We can create
private/lexical variables by “my”. my $a; my ($a, $b); my ($a, $b) = @_

 

Loop control variable $_ (No relation with @_)

  1. use
    strict; # strict check the program

$a $b is not recommended to be used, which are used for
internal variables of “sort” functions.

  1. “return” operation: return some value and exit the
    subroutine (don’t run the existing part of the program)

In some part, we can ignore the & sign when calling subroutine
(which is not recommended)

 

Also subroutine can return a list. (e.g. 1..10).

  1. X
  2. State
    P80---maybe different with static

 

~~~Chapter 5 Input and Output

  1. When
    reaching to end of file, the row input will return “undef” (implication for
    usage of “defined” function)

while(<STDIN>) , while(defined($line=<STDIN>)),
foreach(<STDIN>)

 

  1. Perl 调用其他程序 输出结果
  2. <>: diamond
    operation
  3. ./program a b - c; handle fiel
    a b c and stdin representing by -.
  4.     < > is special case of
    row input operations, it reads from the specific position rather than just
    stdin.
  5. <>: source comes from: @ARGV, STDIN. Check them one by one.
  6. @ARGV: contains the source from the input line. Especially, the name of
    the program is stored in $0 (comparative path).
  7. print @arr; # Print all element with no space in between, that is
    concatenate all together

print “@arr”; # print all with
space separated

print “@arr\n” # print line
break for each of elements with one of them in one row

print sort <>

 

  1. Rule for brace: Unless it can change the meaning, we can ignore the
    braces.
  2. printf: formatted output

Conversion (formation) begins with
% sign

%g: automatically select the
output form of number: float, integer, exp.

%d: decimal integer (ignore the
fractional part)

Specify the width of numbers positive: %6d 
-- with length 6, right justified

Specify the width of numbers negative: %-14d – with length 14, left justified

%s: char format

%f: float format

%12.3 format: width of integer
is 12, width of fractional part is 3

 

For real %, we need special
consideration: %%

  1. printf: contains fixed number of parameters with specified format. When
    we want to use

Array to be parameters of
printf, we can dynamically print the format infor.

my @items=qw\wilma dino
pebbles\;

my $format=” The items are:\n”.
(“%10s\n” x @items);

printf
$format, @items;

  1. Filehandle: name for connection between perl process and outer I/O.

Recommendation: use capital
character to name the filehandles.

6 reserved filehandle: STDIN,
STDOUT, STDERR, DATA, ARGV, ARGVOUT.

./program <dino >wilma; #
input from dino, output to wilma

  1. open: connect perl program to outer source.
    1. open CONFIG, “dino”;   
    2. open CONFIG, “<dino”;        open CONFIG, “<”, “dino”
    3. open BEDROCK, “>fred”;      open BDEROCK, “>”, $file_name;
    4. open LOG, “>>logfile”;         open LOG, “>>”,
      &logfile_name();

1==2: readin from file “dino”; 3: write to fred; 4:
append to logfile

 

my $success=open LOG, “>>logfile”;

this is used to test the success of the open
operations.

 

close filehandle: close BEDROCK;

  1. “die” function: end the program, output the specified information to
    output flow and return non-zero return value.

Traditionally, 0:
success;

1: grammar mistakes;

2: program mistakes;

3: configuration
mistakes.

$!: readable system mistake information

 

e.g.

if (! open LOG, “>>logfile”)
{

die “ Cannot create logfile: $!”;

}

Useful info: check the return
value of “open”.

  1. Usage of filehandle:
  • open PASSWD, “< /etc/passwd”;

while(<PASSWD>){

chomp;

..}

 

<Name of
filehandle>:  to use the info. of
filehandle to read.

filehandle: as row input for in
mode.

for out file handle using
print, printf as keywords to output:

print LOG “…..”;

print STDERR “….”, “…”;

Note: There is no comma between
filehandle and info. to output.

 

  1. “select” to change
    default filehandle, the default one is STDOUT.

select BEDROCK;

print “I hope….”;

print “This is…”;

 

When outputting to filehandle,
the default way to do is using buffer. If one want to refresh immediately, we
can use $|=1 to make it refresh immediately.

 

Multiple Usage of file handle: when
open some handler, and open it again, Perl will close the original one.

  1. “say” has the same usage with “printf”, just have “line break” default
    for each line.

print “name\n”; ==

say “name”;

~~~~~~~~End of Chapter 5~~~~

 

~~~~~Chapter 16 Process Management~~~

  1. system: begin the sub-process of Perl using stin and stdout, stderr of
    Perl.

system  ‘ls –l $HOME’; # Note: HOME is variable of
shell rather than Perl, so we must use single quoted rather than double quoted

Make command to become “background
process” by &;

system ‘ls &’;

system ‘for i in *; do echo == $i ==; cat $i ; done’ ;

system “ls”, “ls –l”…;

multiple parameters?????

  1. exec: same grammar with “system” function except that: it leads the perl
    process to perform function by itself.

exec will
jump into the specified process and no perl process even if the specified
process ended.

situation to use: In case that
perl build env for other program.

each code after exec is useless
since it will not be executed.

 

Traditionally, exec will be
used with fork together.

  1. env variable: PATH. separated by : colon.
  2. backquote to capture
    the output from outer process ``,

we can even use the interpolate
for some vars in `` different from ‘’;

$ax=`perldoc –f $x`

Multiple lines’ output:

@lines= `who`; rather than
$lines= `who`;

  1. Process as filehandle
  • open DATE, “date|”; # date
    output to DATE
  • open MAIL, “|mail Merlyn”;
    #MAIL as input to mail Merlyn

 

  1. x
  2. x
  3. x
  4. x
  5. x
  6. x
  7. x
  8. x

 

 

P Note:

  1. Number and String can transform
    between each other in Perl; Number is saved in “double float” form and there is
    no “integer” type;

e: denotes power 10, 2e10=2^10

Number can be rewritten using
“underline” 2123455=2_123_455

Non-decimal number:

Octal: headed with 0

Hexadecimal: headed with 0x

Binary: head with 0B

  1. @ARGV: keeps the list of
    parameters for perl scripts
  2. $0: save the name of the program,
    same with $ARGV[0]
  3. change dir: chdir “/tmp”;

 

 

 

 

Note:

Reading list:

<Intermediate Perl>
<Learning Perl Student Workbook>: for example, practice

<Perl Programming Language>: big
camel book; this book is small camel book

80-20: 80% function using 20%
documentation, 20% function using 80% documentation

Perl: Practical Extraction and
Reporting Language

Perl Advantage: problem with 90% word
documentation related, 10% business related

CPAN: Comprehensive Perl Archive
Network---for perl source code and other program for Unix

Usage of buffer:

 

say output:

 

原文链接: https://www.cnblogs.com/jsquare/archive/2013/06/08/3127387.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    Perl Summary from Camel Book

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/91703

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月10日 上午1:18
下一篇 2023年2月10日 上午1:18

相关推荐