📄 perl.ms
字号:
.PPThe foreach loop iterates over a normal array value and sets the variableVAR to be each element of the array in turn.The variable is implicitly local to the loop, and regains its former valueupon exiting the loop.The \*(L"foreach\*(R" keyword is actually identical to the \*(L"for\*(R" keyword,so you can use \*(L"foreach\*(R" for readability or \*(L"for\*(R" for brevity.If VAR is omitted, $_ is set to each value.If ARRAY is an actual array (as opposed to an expression returning an arrayvalue), you can modify each element of the arrayby modifying VAR inside the loop.Examples:.nf.ne 5 for (@ary) { s/foo/bar/; } foreach $elem (@elements) { $elem *= 2; }.ne 3 for ((10,9,8,7,6,5,4,3,2,1,\'BOOM\')) { print $_, "\en"; sleep(1); } for (1..15) { print "Merry Christmas\en"; }.ne 3 foreach $item (split(/:[\e\e\en:]*/, $ENV{\'TERMCAP\'})) { print "Item: $item\en"; }.fi.PPThe BLOCK by itself (labeled or not) is equivalent to a loop that executesonce.Thus you can use any of the loop control statements in it to leave orrestart the block.The.I continueblock is optional.This construct is particularly nice for doing case structures..nf.ne 6 foo: { if (/^abc/) { $abc = 1; last foo; } if (/^def/) { $def = 1; last foo; } if (/^xyz/) { $xyz = 1; last foo; } $nothing = 1; }.fiThere is no official switch statement in perl, because thereare already several ways to write the equivalent.In addition to the above, you could write.nf.ne 6 foo: { $abc = 1, last foo if /^abc/; $def = 1, last foo if /^def/; $xyz = 1, last foo if /^xyz/; $nothing = 1; }or.ne 6 foo: { /^abc/ && do { $abc = 1; last foo; }; /^def/ && do { $def = 1; last foo; }; /^xyz/ && do { $xyz = 1; last foo; }; $nothing = 1; }or.ne 6 foo: { /^abc/ && ($abc = 1, last foo); /^def/ && ($def = 1, last foo); /^xyz/ && ($xyz = 1, last foo); $nothing = 1; }or even.ne 8 if (/^abc/) { $abc = 1; } elsif (/^def/) { $def = 1; } elsif (/^xyz/) { $xyz = 1; } else {$nothing = 1;}.fiAs it happens, these are all optimized internally to a switch structure,so perl jumps directly to the desired statement, and you needn't worryabout perl executing a lot of unnecessary statements when you have a stringof 50 elsifs, as long as you are testing the same simple scalar variableusing ==, eq, or pattern matching as above.(If you're curious as to whether the optimizer has done this for a particularcase statement, you can use the \-D1024 switch to list the syntax treebefore execution.).Sh "Simple statements"The only kind of simple statement is an expression evaluated for its sideeffects.Every simple statement must be terminated with a semicolon, unless it is thefinal statement in a block, in which case the semicolon is optional.(Semicolon is still encouraged there if the block takes up more than one line)..PPAny simple statement may optionally be followed by asingle modifier, just before the terminating semicolon.The possible modifiers are:.nf.ne 4 if EXPR unless EXPR while EXPR until EXPR.fiThe.I ifand.I unlessmodifiers have the expected semantics.The.I whileand.I untilmodifiers also have the expected semantics (conditional evaluated first),except when applied to a do-BLOCK or a do-SUBROUTINE command,in which case the block executes once before the conditional is evaluated.This is so that you can write loops like:.nf.ne 4 do { $_ = <STDIN>; .\|.\|. } until $_ \|eq \|".\|\e\|n";.fi(See the.I dooperator below. Note also that the loop control commands described later willNOT work in this construct, since modifiers don't take loop labels.Sorry.).Sh "Expressions"Since.I perlexpressions work almost exactly like C expressions, only the differenceswill be mentioned here..PPHere's what.I perlhas that C doesn't:.Ip ** 8 2The exponentiation operator..Ip **= 8The exponentiation assignment operator..Ip (\|) 8 3The null list, used to initialize an array to null..Ip . 8Concatenation of two strings..Ip .= 8The concatenation assignment operator..Ip eq 8String equality (== is numeric equality).For a mnemonic just think of \*(L"eq\*(R" as a string.(If you are used to the.I awkbehavior of using == for either string or numeric equalitybased on the current form of the comparands, beware!You must be explicit here.).Ip ne 8String inequality (!= is numeric inequality)..Ip lt 8String less than..Ip gt 8String greater than..Ip le 8String less than or equal..Ip ge 8String greater than or equal..Ip cmp 8String comparison, returning -1, 0, or 1..Ip <=> 8Numeric comparison, returning -1, 0, or 1..Ip =~ 8 2Certain operations search or modify the string \*(L"$_\*(R" by default.This operator makes that kind of operation work on some other string.The right argument is a search pattern, substitution, or translation.The left argument is what is supposed to be searched, substituted, ortranslated instead of the default \*(L"$_\*(R".The return value indicates the success of the operation.(If the right argument is an expression other than a search pattern,substitution, or translation, it is interpreted as a search patternat run time.This is less efficient than an explicit search, since the pattern mustbe compiled every time the expression is evaluated.)The precedence of this operator is lower than unary minus and autoincrement/decrement, but higher than everything else..Ip !~ 8Just like =~ except the return value is negated..Ip x 8The repetition operator.Returns a string consisting of the left operand repeated thenumber of times specified by the right operand.In an array context, if the left operand is a list in parens, it repeatsthe list..nf print \'\-\' x 80; # print row of dashes print \'\-\' x80; # illegal, x80 is identifier print "\et" x ($tab/8), \' \' x ($tab%8); # tab over @ones = (1) x 80; # an array of 80 1's @ones = (5) x @ones; # set all elements to 5.fi.Ip x= 8The repetition assignment operator.Only works on scalars..Ip .\|. 8The range operator, which is really two different operators dependingon the context.In an array context, returns an array of values counting (by ones)from the left value to the right value.This is useful for writing \*(L"for (1..10)\*(R" loops and for doingslice operations on arrays..SpIn a scalar context, .\|. returns a boolean value.The operator is bistable, like a flip-flop, andemulates the line-range (comma) operator of sed, awk, and various editors.Each .\|. operator maintains its own boolean state.It is false as long as its left operand is false.Once the left operand is true, the range operator stays trueuntil the right operand is true,AFTER which the range operator becomes false again.(It doesn't become false till the next time the range operator is evaluated.It can test the right operand and become false on thesame evaluation it became true (as in awk), but it still returns true once.If you don't want it to test the right operand till the nextevaluation (as in sed), use three dots (.\|.\|.) instead of two.)The right operand is not evaluated while the operator is in the \*(L"false\*(R" state,and the left operand is not evaluated while the operator is in the \*(L"true\*(R" state.The precedence is a little lower than || and &&.The value returned is either the null string for false, or a sequence number(beginning with 1) for true.The sequence number is reset for each range encountered.The final sequence number in a range has the string \'E0\' appended to it, whichdoesn't affect its numeric value, but gives you something to search for if youwant to exclude the endpoint.You can exclude the beginning point by waiting for the sequence number to begreater than 1.If either operand of scalar .\|. is static, that operand is implicitly comparedto the $. variable, the current line number.Examples:.nf.ne 6As a scalar operator: if (101 .\|. 200) { print; } # print 2nd hundred lines next line if (1 .\|. /^$/); # skip header lines s/^/> / if (/^$/ .\|. eof()); # quote body.ne 4As an array operator: for (101 .\|. 200) { print; } # print $_ 100 times @foo = @foo[$[ .\|. $#foo]; # an expensive no-op @foo = @foo[$#foo-4 .\|. $#foo]; # slice last 5 items.fi.Ip \-x 8A file test.This unary operator takes one argument, either a filename or a filehandle,and tests the associated file to see if something is true about it.If the argument is omitted, tests $_, except for \-t, which tests.IR STDIN .It returns 1 for true and \'\' for false, or the undefined value if thefile doesn't exist.Precedence is higher than logical and relational operators, but lower thanarithmetic operators.The operator may be any of:.nf \-r File is readable by effective uid/gid. \-w File is writable by effective uid/gid. \-x File is executable by effective uid/gid. \-o File is owned by effective uid. \-R File is readable by real uid/gid. \-W File is writable by real uid/gid. \-X File is executable by real uid/gid. \-O File is owned by real uid. \-e File exists. \-z File has zero size. \-s File has non-zero size (returns size). \-f File is a plain file. \-d File is a directory. \-l File is a symbolic link. \-p File is a named pipe (FIFO). \-S File is a socket. \-b File is a block special file. \-c File is a character special file. \-u File has setuid bit set. \-g File has setgid bit set. \-k File has sticky bit set. \-t Filehandle is opened to a tty. \-T File is a text file. \-B File is a binary file (opposite of \-T). \-M Age of file in days when script started. \-A Same for access time. \-C Same for inode change time..fiThe interpretation of the file permission operators \-r, \-R, \-w, \-W, \-x and \-Xis based solely on the mode of the file and the uids and gids of the user.There may be other reasons you can't actually read, write or execute the file.Also note that, for the superuser, \-r, \-R, \-w and \-W always return 1, and \-x and \-X return 1 if any execute bit is set in the mode.Scripts run by the superuser may thus need to do a stat() in order to determinethe actual mode of the file, or temporarily set the uid to something else..SpExample:.nf.ne 7 while (<>) { chop; next unless \-f $_; # ignore specials .\|.\|. }.fiNote that \-s/a/b/ does not do a negated substitution.Saying \-exp($foo) still works as expected, however\*(--only single lettersfollowing a minus are interpreted as file tests..SpThe \-T and \-B switches work as follows.The first block or so of the file is examined for odd characters such asstrange control codes or metacharacters.If too many odd characters (>10%) are found, it's a \-B file, otherwise it's a \-T file.Also, any file containing null in the first block is considered a binary file.If \-T or \-B is used on a filehandle, the current stdio buffer is examinedrather than the first block.Both \-T and \-B return TRUE on a null file, or a file at EOF when testinga filehandle..PPIf any of the file tests (or either stat operator) are given the specialfilehandle consisting of a solitary underline, then the stat structureof the previous file test (or stat operator) is used, saving a systemcall.(This doesn't work with \-t, and you need to remember that lstat and -lwill leave values in the stat structure for the symbolic link, not thereal file.)Example:.nf print "Can do.\en" if -r $a || -w _ || -x _;.ne 9 stat($filename); print "Readable\en" if -r _; print "Writable\en" if -w _; print "Executable\en" if -x _; print "Setuid\en" if -u _; print "Setgid\en" if -g _; print "Sticky\en" if -k _; print "Text\en" if -T _; print "Binary\en" if -B _;.fi.PPHere is what C has that.I perldoesn't:.Ip "unary &" 12Address-of operator..Ip "unary *" 12Dereference-address operator..Ip "(TYPE)" 12Type casting operator..PPLike C,.I perldoes a certain amount of expression evaluation at compile time, wheneverit determines that all of the arguments to an operator are static and haveno side effects.In particular, string concatenation happens at compile time between literals that don't do variable substitution.Backslash interpretation also happens at compile time.You can say.nf.ne 2 \'Now is the time for all\' . "\|\e\|n" . \'good men to come to.\'.fiand this all reduces to one string internally..PPThe autoincrement operator has a little extra built-in magic to it.If you increment a variable that is numeric, or that has ever been used ina numeric context, you get a normal increment.If, however, the variable has only been used in string contexts since itwas set, and has a value that is not null and matches the
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -