perldata.pod

来自「MSYS在windows下模拟了一个类unix的终端」· POD 代码 · 共 830 行 · 第 1/3 页

POD
830
字号
String literals are usually delimited by either single or doublequotes.  They work much like quotes in the standard Unix shells:double-quoted string literals are subject to backslash and variablesubstitution; single-quoted strings are not (except for C<\'> andC<\\>).  The usual C-style backslash rules apply for makingcharacters such as newline, tab, etc., as well as some more exoticforms.  See L<perlop/"Quote and Quote-like Operators"> for a list.Hexadecimal, octal, or binary, representations in string literals(e.g. '0xff') are not automatically converted to their integerrepresentation.  The hex() and oct() functions make these conversionsfor you.  See L<perlfunc/hex> and L<perlfunc/oct> for more details.You can also embed newlines directly in your strings, i.e., they can endon a different line than they begin.  This is nice, but if you forgetyour trailing quote, the error will not be reported until Perl findsanother line containing the quote character, which may be much furtheron in the script.  Variable substitution inside strings is limited toscalar variables, arrays, and array or hash slices.  (In other words,names beginning with $ or @, followed by an optional bracketedexpression as a subscript.)  The following code segment prints out "Theprice is $Z<>100."    $Price = '$100';	# not interpreted    print "The price is $Price.\n";	# interpretedAs in some shells, you can enclose the variable name in braces todisambiguate it from following alphanumerics (and underscores).You must also dothis when interpolating a variable into a string to separate thevariable name from a following double-colon or an apostrophe, sincethese would be otherwise treated as a package separator:    $who = "Larry";    print PASSWD "${who}::0:0:Superuser:/:/bin/perl\n";    print "We use ${who}speak when ${who}'s here.\n";Without the braces, Perl would have looked for a $whospeak, aC<$who::0>, and a C<$who's> variable.  The last two would be the$0 and the $s variables in the (presumably) non-existent packageC<who>.In fact, an identifier within such curlies is forced to be a string,as is any simple identifier within a hash subscript.  Neither needquoting.  Our earlier example, C<$days{'Feb'}> can be written asC<$days{Feb}> and the quotes will be assumed automatically.  Butanything more complicated in the subscript will be interpreted asan expression.A literal of the form C<v1.20.300.4000> is parsed as a string composedof characters with the specified ordinals.  This provides an alternative,more readable way to construct strings, rather than use the somewhat lessreadable interpolation form C<"\x{1}\x{14}\x{12c}\x{fa0}">.  This is usefulfor representing Unicode strings, and for comparing version "numbers"using the string comparison operators, C<cmp>, C<gt>, C<lt> etc.If there are two or more dots in the literal, the leading C<v> may beomitted.    print v9786;              # prints UTF-8 encoded SMILEY, "\x{263a}"    print v102.111.111;       # prints "foo"    print 102.111.111;        # sameSuch literals are accepted by both C<require> and C<use> fordoing a version check.  The C<$^V> special variable also contains therunning Perl interpreter's version in this form.  See L<perlvar/$^V>.The special literals __FILE__, __LINE__, and __PACKAGE__represent the current filename, line number, and package name at thatpoint in your program.  They may be used only as separate tokens; theywill not be interpolated into strings.  If there is no current package(due to an empty C<package;> directive), __PACKAGE__ is the undefinedvalue.The two control characters ^D and ^Z, and the tokens __END__ and __DATA__may be used to indicate the logical end of the script before the actualend of file.  Any following text is ignored.Text after __DATA__ but may be read via the filehandle C<PACKNAME::DATA>,where C<PACKNAME> is the package that was current when the __DATA__token was encountered.  The filehandle is left open pointing to thecontents after __DATA__.  It is the program's responsibility toC<close DATA> when it is done reading from it.  For compatibility witholder scripts written before __DATA__ was introduced, __END__ behaveslike __DATA__ in the toplevel script (but not in files loaded withC<require> or C<do>) and leaves the remaining contents of thefile accessible via C<main::DATA>.See L<SelfLoader> for more description of __DATA__, andan example of its use.  Note that you cannot read from the DATAfilehandle in a BEGIN block: the BEGIN block is executed as soonas it is seen (during compilation), at which point the corresponding__DATA__ (or __END__) token has not yet been seen.A word that has no other interpretation in the grammar willbe treated as if it were a quoted string.  These are known as"barewords".  As with filehandles and labels, a bareword that consistsentirely of lowercase letters risks conflict with future reservedwords, and if you use the C<use warnings> pragma or the B<-w> switch, Perl will warn you about anysuch words.  Some people may wish to outlaw barewords entirely.  If yousay    use strict 'subs';then any bareword that would NOT be interpreted as a subroutine callproduces a compile-time error instead.  The restriction lasts to theend of the enclosing block.  An inner block may countermand thisby saying C<no strict 'subs'>.Arrays and slices are interpolated into double-quoted stringsby joining the elements with the delimiter specified in the C<$">variable (C<$LIST_SEPARATOR> in English), space by default.  Thefollowing are equivalent:    $temp = join($", @ARGV);    system "echo $temp";    system "echo @ARGV";Within search patterns (which also undergo double-quotish substitution)there is an unfortunate ambiguity:  Is C</$foo[bar]/> to be interpreted asC</${foo}[bar]/> (where C<[bar]> is a character class for the regularexpression) or as C</${foo[bar]}/> (where C<[bar]> is the subscript to array@foo)?  If @foo doesn't otherwise exist, then it's obviously acharacter class.  If @foo exists, Perl takes a good guess about C<[bar]>,and is almost always right.  If it does guess wrong, or if you're justplain paranoid, you can force the correct interpretation with curlybraces as above.A line-oriented form of quoting is based on the shell "here-document"syntax.  Following a C<< << >> you specify a string to terminatethe quoted material, and all lines following the current line down tothe terminating string are the value of the item.  The terminatingstring may be either an identifier (a word), or some quoted text.  Ifquoted, the type of quotes you use determines the treatment of thetext, just as in regular quoting.  An unquoted identifier works likedouble quotes.  There must be no space between the C<< << >> andthe identifier, unless the identifier is quoted.  (If you put a space itwill be treated as a null identifier, which is valid, and matches the firstempty line.)  The terminating string must appear by itself (unquoted andwith no surrounding whitespace) on the terminating line.	print <<EOF;    The price is $Price.    EOF	print << "EOF";	# same as above    The price is $Price.    EOF	print << `EOC`;	# execute commands    echo hi there    echo lo there    EOC	print <<"foo", <<"bar";	# you can stack them    I said foo.    foo    I said bar.    bar	myfunc(<< "THIS", 23, <<'THAT');    Here's a line    or two.    THIS    and here's another.    THATJust don't forget that you have to put a semicolon on the endto finish the statement, as Perl doesn't know you're not going totry to do this:	print <<ABC    179231    ABC	+ 20;If you want your here-docs to be indented with the rest of the code, you'll need to remove leading whitespacefrom each line manually:    ($quote = <<'FINIS') =~ s/^\s+//gm;	The Road goes ever on and on, 	down from the door where it began.    FINISIf you use a here-doc within a delimited construct, such as in C<s///eg>,the quoted material must come on the lines following the final delimiter.So instead of    s/this/<<E . 'that'    the other    E     . 'more '/eg;you have to write    s/this/<<E . 'that'      . 'more '/eg;     the other     E If the terminating identifier is on the last line of the program, youmust be sure there is a newline after it; otherwise, Perl will give thewarning B<Can't find string terminator "END" anywhere before EOF...>.Additionally, the quoting rules for the identifier are not related toPerl's quoting rules -- C<q()>, C<qq()>, and the like are not supportedin place of C<''> and C<"">, and the only interpolation is for backslashingthe quoting character:    print << "abc\"def";    testing...    abc"defFinally, quoted strings cannot span multiple lines.  The general rule isthat the identifier must be a string literal.  Stick with that, and youshould be safe.=head2 List value constructorsList values are denoted by separating individual values by commas(and enclosing the list in parentheses where precedence requires it):    (LIST)In a context not requiring a list value, the value of what appearsto be a list literal is simply the value of the final element, aswith the C comma operator.  For example,    @foo = ('cc', '-E', $bar);assigns the entire list value to array @foo, but    $foo = ('cc', '-E', $bar);assigns the value of variable $bar to the scalar variable $foo.Note that the value of an actual array in scalar context is thelength of the array; the following assigns the value 3 to $foo:    @foo = ('cc', '-E', $bar);    $foo = @foo;		# $foo gets 3You may have an optional comma before the closing parenthesis of alist literal, so that you can say:    @foo = (	1,	2,	3,    );To use a here-document to assign an array, one line per element,you might use an approach like this:    @sauces = <<End_Lines =~ m/(\S.*\S)/g;	normal tomato	spicy tomato	green chile	pesto	white wine    End_LinesLISTs do automatic interpolation of sublists.  That is, when a LIST isevaluated, each element of the list is evaluated in list context, andthe resulting list value is interpolated into LIST just as if eachindividual element were a member of LIST.  Thus arrays and hashes lose theiridentity in a LIST--the list    (@foo,@bar,&SomeSub,%glarch)contains all the elements of @foo followed by all the elements of @bar,followed by all the elements returned by the subroutine named SomeSub called in list context, followed by the key/value pairs of %glarch.To make a list reference that does I<NOT> interpolate, see L<perlref>.

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?