Perl Summary from Camel Book
- first line: #!/usr/bin/perl
- 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)
- chmod a+x program // using in shell a+x = 755
- print “ …\n” ;== say “…..”-----Not necessary to input “\n” compared with print, otherwise same function
- The end of one line is denoted by semicolon (;)
- ` ….. ` ---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; }
- 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
- 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)
- Double quoted string: more powerful, we can use variables, expressions
- 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
- 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
- Inner build the “warning” function
- #!/usr/bin/perl –w
- perl –w program
- #!/usr/bin/perl
use warnings;
- use diagnostics; giving the detailed explanation for the mistakes; perl –Mdiagnostics program;
- 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)
- Number comparison: same with C++
String comparison: lt, gt, eq le, ge, ne (The order of Uppercase is before Lowercase)
- if(…) {…} else {….}
No Boolean variable in Perl; “0” =0;
To get reverse Boolean value: !$express
- Line input for the standard input (<STDIN>):
$line=<STDIN>
- 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
- while(…) {….}
- “undef” type: before assignment, the type of variable is undef, for number 0, for string null. But undef is neither number nor string.
- 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~~
- 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],….
- 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
- list: (a, b, c)
.. : Range Operator; (1..100) 1,2,3,4,100
(5..1): null list, it can only increase by using ...
- 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
- 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
- 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)
- 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
- 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
- foreach $x qw(a b c) {}
- 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 $_
- 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
- 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;
- Scalar context and list context according to the context.
In scalar context, @arr returns the number of element in @arr.
- 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
- 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.)
- 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 @_)
- use strict; # strict check the program
$a $b is not recommended to be used, which are used for internal variables of “sort” functions.
- “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).
- X
- State P80---maybe different with static
~~~Chapter 5 Input and Output
- 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>)
- Perl 调用其他程序 输出结果
- <>: diamond operation
- ./program a b - c; handle fiel a b c and stdin representing by -.
- < > is special case of row input operations, it reads from the specific position rather than just stdin.
- <>: source comes from: @ARGV, STDIN. Check them one by one.
- @ARGV: contains the source from the input line. Especially, the name of the program is stored in $0 (comparative path).
- 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 <>
- Rule for brace: Unless it can change the meaning, we can ignore the braces.
- 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: %%
- 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;
- 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
- open: connect perl program to outer source.
- open CONFIG, “dino”;
- open CONFIG, “<dino”; open CONFIG, “<”, “dino”
- open BEDROCK, “>fred”; open BDEROCK, “>”, $file_name;
- 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;
- “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”.
- 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.
- “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.
- “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~~~
- 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?????
- 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.
- env variable: PATH. separated by : colon.
- 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`;
- Process as filehandle
- open DATE, “date|”; # date output to DATE
- open MAIL, “|mail Merlyn”; #MAIL as input to mail Merlyn
- x
- x
- x
- x
- x
- x
- x
- x
P Note:
- 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
- @ARGV: keeps the list of parameters for perl scripts
- $0: save the name of the program, same with $ARGV[0]
- 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: