单行Perl教程

所需积分/C币:9 2014-09-04 22:37:51 266KB PDF
17
收藏 收藏
举报

Perl的用户中,有不少喜欢写单行的Perl 单行Perl更方便 本文是单行Perl的一个基本教程
One-liners 2.1 Standard input Code listing 8: Skipping comments prompts cat afile I perl -e 'while (<>)i print unless /\s+#/y' The ""(pipe) symbol takes the output of cat and makes it the standard input of my Perl program. The diamond operator, <> reads lines from standard input, so this one-liner reads the lines from afile and then prints the lines that do not match the regular expression \s+# I can also redirect file contents to perls standard input using the shell redirection operator, < Code listing 9 produces the salle output as the previous example Code Listing 9: Input by redirection prompts perl -e 'while (<>)i print unless /\s+#/),< afile However, the diamond operator can open and directly rea.d the contents of the file specified on the command line so i do not need to redirect the file contents myself. Code listing 10 does not use file redirection, and does the same thing as code listing 9 Code Listing 10 prompts perl -e while (<>)i print unless /\s+#/F'afile 2.2 Command line arguments I can access command line arguments using OARGV. Code listing 1l simply prints whatever is in ARGV Code Listing 11: Print the command line arguments prompts perl -e print "OARGV\n", Foo Bar Bletch Foo Bar bletch Suppose I have a file that contains a list of files, one filename per line, that i want to manipulate. I can see the file names when I list the files in code listing 12 Code Listing 12: The filenames in files. txt Pr。mpt$ cat fi1es.txt afile2 afire The unix utility xargs can transpose its standard input into arguments for another command. I want to take this list of filenames and make them the arguments of the we command so I can count the number of lines The Perl review(0, 1 b 112)3 ne-iners in each file. In code listing 13 the xargs command takes its standard input, the list of filenames, and makes them the arguments for w Code Listing 13: Count lines in files prompt cat files. txt I xargs wc -l 54 afile2 162 total Code listing 13 is the same as if I typed this directly, as in code listing 14 Code listing 14: Count lines in files prompt wc -l afile1 afile2 afile3 2.3 Playing with find n code listing 15 I reimplement the find command option "type d"using a perl one-liner and xargs. The find command recursively outputs a list of filenames starting from a specified directory and matching certain criteria. In this case, the criteria, " -type d", lists only directories Code listing 15: Using find prompt find I xargs perl -e gargv= grep( -d $-, @ARGV); print "@ARGV 2 The xargs comand takes the list of filenames and makes them the arguments to the one-liner in code listing 15. The one-liner then uses a grep expression to filter @ARGV for filenames that, are directories using the d file test operator and then prints the results 3 Useful command line switches Perl command line options shorten one-liners by adding automatic processing to the small script i create using the -e option. Perl has many other useful options besides the ones I show. See the perlrun manual page for the detail 3.1 The -e switch The perl interpreter takes each -e argument as a fragment of Perl code and executes it. Each -e switch on the command line is taken as a line in a script. If I paste the contents of each -e switch into a file, and run Perl on that file. I have the exact same effect as the -e switch. Code listing 16 rewrites code listing 1 with two -e switches The Perl revie(0,1b112)·4 One-liners Code listing 16: Multiple -e switches prompts perl -e print "Hello ";'-e print world \n";' Hello world Each codc bit (in thc outcr singlc quotes) is a singlc string that thc sholl parses as a scparate token, so tho shell sees the four tokens in code listing 17 Code Listing 17: Multiple -e switches, as tokens print Hello print "world\n"; 3.2 The -n switch The -n switch wraps a whilc loop around your program. In codc listing 18, the loop reads lincs of input with the diamond operator, sets s to the contents of each line, the the code bits I specify with the -e tch de listing 18: Usin g while (<> <-e argument> In code listing 19 I create my own cat program Code listing 19: Reimplementing cat prompts perl -ne 'print $_, afile 3.3 The -p switch The -p switch does the same thing and prints the value of s-at the end of each iteration g g - p hi1e(<>){ gument> <-e argument> The Perl Review(, 1 b 112).5 ne-iners In code listing 20 the loop reads lines in standard input, sets s to the contents of each line, executes the -e args, and then prints $ I can use this to modify lines from an output listing For example, I can remove the permissions column on a" -output file listing. In code listing 21 I substitute the first group of non-whitespace and the space after it with nothing Code Listing 21: Remove the first column prompts ls -l I perl -pe 's/\S+//' 3.4 Using modules I can use modules on the command line with the -M switch. The -M<module> switch is the equivalent of including"use <module>; in the virtual scripts I create. In code listing 22, I use the 10: Handle module to set the standard output autoflush option Code Listing 22: Using modules prompts cat afile I perl -MIO: Handle -e STDOUT->autoflush(1); while (<>)i print j Normally, I use strict and turn on warnings in my scripts and I can do this in one-liners as well. In code listing 23 I include the strict module with-Mstrict, and turn on warnings by adding-W Code Listing 23: Using strict prompt cat afile I perl -W -Strict -e 'my var = 17; print $var> If i do not declare Svar, the strict module catches it as it does in code listing 24 Code Listing 24: Undeclared variables prompts cat afile I perl -w-Mstrict -e '$var =17; print var Global symbol "var"requires explicit package name at -e line 1 Execution of -e aborted due to compilation errors In code listing 25, Perl warns about Svar which I used without initializing it Code Listing 25: Uninitialized variables cat afile I perl -w-Mstrict -e 'my var: print var Use of uninitialized value at -e line 1 4 Wrestling with the shell Quote marks, double and single, as well as the dollar sign, are part of the shell syntax. If I need to use thesc characters in my string, I must cscapc them. Each shell has a slightly diffcrent syntax for its spccial The Perl review(0, 1 b 112 )6 ne-iners characters, and different platforms may handle escaping them differently. Code listing 26 shows several examples of escaping shell metacharacters Code Listing 26: Escaping shell metacharacters prompts echo "the variable \SUSER is "\"SUSER"\" the variable USER is "bay I can do several things to avoid shell quoting problems. In code listing 27, the program outputs a malformed SQL statement bccausc thc literal a3 is not quoted. The singlc quotes disappcar bccausc I uscd singlc quote for my -e code bit, but I need quotes around a3 so the SQL parser knows that a3 is a literal string and not a column name Code listing 27: Misq SQL prompt perl -e ' print "select from foo where bar=a3\n") select from foo where bar =a3 In code lisitng 28 I use Perls chr( function to add any literal character (including quotes)using its ordina asci value. I can conca tenate chr(39), the single quote, with the rest of the SQL, string Code Listing 28: Using chro to get literal values prompts perl -e 'print "select from foo where bar=". chr (39) chr(39) select from foo where bar=a33 In code listing 29 I use the generalized quote operators, q and q, instead of single and double quotes. I can use single or double ticks inside the resulting perl string because they are no longer delimiters Code listing 29: Generalized quotes prompts perl -e ' print qq#select from foo where bar=a3 \n# select f foo where bar=a3 Code listing 30 uses the back-whack character, "\" to escape the quote marks, but the syntax is rather unwieldy-\,,. In most shells, I have to close the prior string with the first tick, then put in the literal tick with a back-whack, and then start the next string with a third tick. The shell then concatenates those strings into a single string bcforc it cxccutcs them Code Listing 30: Escaping quote characters prompt perl -e 'print select count (*)from foo where bar =,\2a3)\>>\n") select from foo where bar =?a3 5 Start and end tricks I can execute code before or after my -e program with the begin or END keyword respectively. The END block in codc listing 31 prints the sum aftcr the whilc loop finishes The Perl revie(0,1b112)·7 ne-iners Code Listing 31: ENd bloc 13 -lAF I perl -ne 'next if /d/;$sum +=(split)[4]: ENDi print "sum\n"j3 In code listing 32 the BEGin executes its block before an implicit loop starts. I can initialize the variable Ssum to 1024 before the loop begins if i use a begin block Code listing 32 begin block Is -IAF I perl -ne BEGIN[Ssum=1024] next if /d/; Ssum +=(split)[4]; ENDi print "Ssum \n"] 6 References Chapter 6, "Social Engineering, Cooperating with Command Interpreters", Programming Perl -Larry Wa.Il Christiansen. Jon Orwant The following perl manual pages come with the standard Perl distribution and can be found online at Perldoc.colll,http://www.perldoc.coll,orfronnthecolnanldlinewith"perldocpagenaine rerun- perl interpreter options perlfag3"Why donI't Perl one-liners work on Inly DOS/ Mac/VMS systeIn? Thefollowingunixmanualpagesmaybefoundonlineatseveralsitesincludinghttp://www.bsdi.com/bsdi- man/, or from the command line with"man pagename ●find ●WC ● xargs The Perl Review(0, 1 b 112). 8

...展开详情
试读 8P 单行Perl教程
立即下载 身份认证后 购VIP低至7折
一个资源只可评论一次,评论内容不能少于5个字
shuiku 资源很好,非常感谢分享。
2018-04-13
回复
shuaigechenzhe 还行。就是没介绍如何setup 环境变量。电路设计也是很需要perl这种脚本语言的。如果能介绍下如何设置环境变量就更好了
2014-09-05
回复
您会向同学/朋友/同事推荐我们的CSDN下载吗?
谢谢参与!您的真实评价是我们改进的动力~
上传资源赚钱or赚积分
最新推荐
单行Perl教程 9积分/C币 立即下载
1/8
单行Perl教程第1页
单行Perl教程第2页

试读结束, 可继续读1页

9积分/C币 立即下载