设为首页 收藏本站
查看: 583|回复: 0

[经验分享] Perl Summary from Camel Book

[复制链接]

尚未签到

发表于 2015-12-27 09:05:37 | 显示全部楼层 |阅读模式

  • 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 havetwo or more “line break”, chomp can only drop one
  

  • while(…) {….}
  • “undef” type: before assignment, the type of variable is undef, fornumber 0, for string null. But undef is neither number nor string.
  • When reading end-of-file, <STDIN> will return undef; To decide astring 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 0increasingly; No limit for the size of list/array
  Namespace for array and scalarvariable is separated.
  When using expression as indexand 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 lastelement
  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 onlyincrease by using ...
  

  • qw: quoted word/ quoted by whitespace++++++ build easy word list
  e.g.qw(a b c)    --&agrave; (“a”, “b”, “c”)
  qw##   !! <> []{}() //
  anything in qw is set as the singlequoted string

  • Assignment for list: ($a, $b, $c) = (x, y, z)
  ($a, $b) = ($b, $a) // exchangethe value, it first builds the list in the right, and then assign it the listin the left.
  Reference to the array, justadd @ before the name of array
  @arr=qw\a b c\;
  ($calar scalar; @rrayarray—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 rightof the array;
  pop delete the last one andreturn this value
  $a1=pop(@arr); // sometimes, wejust use “pop @arr;”—void context, there is no place to hold the returned value.
  
  push: push one or a list ofelements 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 theleft(lower index) of the array
  shift: delete the first elementfrom 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 thecopy of the element of @arr, it’s reference to @each element of @arr, themodification to $x will lead to the modification of @arr;
  Also, the control/loop variablewill not change the value of control variable $x
  
  If one ignores to specify thecontrol variable, then the default control variable is $_

  • reverse: return the reverse list for agiven list
  @a1=reverse(@arr)
  This is reference by value andwill not change the values of original array @arr

  • sort: by ASCII coding, Uppercasesmaller than Lowercase, Number smaller than character (upper and lower case)
  reference by value and will notchange parameter
  @arr= sort @arr;

  • Scalar context and list context according to the context.
  In scalarcontext, @arr returns the number of element in @arr.
  

  • Scalarcontext and list context
  The explanation of scalar or array or list depends onthe context
  $a1= @arr;   $a1is 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 endof 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

  • Definesub program: sub abc{ }
  It can be placed any place in the program. Sub programhas independent namespace. (Program with same name, the later one will behidden by the use of the first one.)

  • Callsub program using the &
  Each sub program will have a returnvalue, which is the result of the last operation.
  #: as the beginning of comment.
  
  There can be parameters in thesubroutines. 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 createprivate/lexical variables by “my”. my $a; my ($a, $b); my ($a, $b) = @_
  
  Loop control variable $_ (No relation with @_)

  • usestrict; # strict check the program
  $a $b is not recommended to be used, which are used forinternal variables of “sort” functions.

  • “return” operation: return some value and exit thesubroutine (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
  • StateP80---maybe different with static
  
  ~~~Chapter 5 Input and Output

  • Whenreaching to end of file, the row input will return “undef” (implication forusage of “defined” function)
  while(<STDIN>) , while(defined($line=<STDIN>)),foreach(<STDIN>)
  

  • Perl 调用其他程序 输出结果
  • <>: diamondoperation
  • ./program a b - c; handle fiela b c and stdin representing by -.
  •     < > is special case ofrow input operations, it reads from the specific position rather than juststdin.
  • <>: source comes from: @ARGV, STDIN. Check them one by one.
  • @ARGV: contains the source from the input line. Especially, the name ofthe program is stored in $0 (comparative path).
  • print @arr; # Print all element with no space in between, that isconcatenate all together
  print “@arr”; # print all withspace separated
  print “@arr\n” # print linebreak 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 thebraces.
  • printf: formatted output
  Conversion (formation) begins with% sign
  %g: automatically select theoutput form of number: float, integer, exp.
  %d: decimal integer (ignore thefractional 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 integeris 12, width of fractional part is 3
  
  For real %, we need specialconsideration: %%

  • printf: contains fixed number of parameters with specified format. Whenwe want to use
  Array to be parameters ofprintf, we can dynamically print the format infor.
  my @items=qw\wilma dinopebbles\;
  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 capitalcharacter 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 openoperations.
  
  close filehandle: close BEDROCK;

  • “die” function: end the program, output the specified information tooutput flow and return non-zero return value.
  Traditionally, 0:success;
  1: grammar mistakes;
  2: program mistakes;
  3: configurationmistakes.
  $!: readable system mistake information
  
  e.g.
  if (! open LOG, “>>logfile”){
  die “ Cannot create logfile: $!”;
  }
  Useful info: check the returnvalue of “open”.

  • Usage of filehandle:


  • open PASSWD, “< /etc/passwd”;
  while(<PASSWD>){
  chomp;
  ..}
  
  <Name offilehandle>:  to use the info. offilehandle to read.
  filehandle: as row input for inmode.
  for out file handle usingprint, printf as keywords to output:
  print LOG “…..”;
  print STDERR “….”, “…”;
  Note: There is no comma betweenfilehandle and info. to output.
  

  • “select” to changedefault 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, wecan use $|=1 to make it refresh immediately.
  
  Multiple Usage of file handle: whenopen some handler, and open it again, Perl will close the original one.

  • “say” has the same usage with “printf”, just have “line break” defaultfor 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 ofPerl.
  system  ‘ls –l $HOME’; # Note: HOME is variable ofshell rather than Perl, so we must use single quoted rather than double quoted
  Make command to become “backgroundprocess” 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 perlprocess to perform function by itself.
  exec willjump into the specified process and no perl process even if the specifiedprocess ended.
  situation to use: In case thatperl build env for other program.
  each code after exec is uselesssince it will not be executed.
  
  Traditionally, exec will beused with fork together.

  • env variable: PATH. separated by : colon.
  • backquote to capturethe output from outer process ``,
  we can even use the interpolatefor some vars in `` different from ‘’;
  $ax=`perldoc –f $x`
  Multiple lines’ output:
  @lines= `who`; rather than$lines= `who`;

  • Process as filehandle


  • open DATE, “date|”; # dateoutput 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 transformbetween each other in Perl; Number is saved in “double float” form and there isno “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 ofparameters 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>: bigcamel book; this book is small camel book
  80-20: 80% function using 20%documentation, 20% function using 80% documentation
  Perl: Practical Extraction andReporting Language
  Perl Advantage: problem with 90% worddocumentation related, 10% business related
  CPAN: Comprehensive Perl ArchiveNetwork---for perl source code and other program for Unix
  Usage of buffer:
  
  say output:
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-156811-1-1.html 上篇帖子: [Win32::Console]Perl终端版生命游戏 下篇帖子: perl-5.14.0在新版gcc中编译不通过解决办法
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表