Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

603 lines
24 KiB

  1. =head1 NAME
  2. perldata - Perl data types
  3. =head1 DESCRIPTION
  4. =head2 Variable names
  5. Perl has three data structures: scalars, arrays of scalars, and
  6. associative arrays of scalars, known as "hashes". Normal arrays are
  7. indexed by number, starting with 0. (Negative subscripts count from
  8. the end.) Hash arrays are indexed by string.
  9. Values are usually referred to by name (or through a named reference).
  10. The first character of the name tells you to what sort of data
  11. structure it refers. The rest of the name tells you the particular
  12. value to which it refers. Most often, it consists of a single
  13. I<identifier>, that is, a string beginning with a letter or underscore,
  14. and containing letters, underscores, and digits. In some cases, it
  15. may be a chain of identifiers, separated by C<::> (or by C<'>, but
  16. that's deprecated); all but the last are interpreted as names of
  17. packages, to locate the namespace in which to look
  18. up the final identifier (see L<perlmod/Packages> for details).
  19. It's possible to substitute for a simple identifier an expression
  20. that produces a reference to the value at runtime; this is
  21. described in more detail below, and in L<perlref>.
  22. There are also special variables whose names don't follow these
  23. rules, so that they don't accidentally collide with one of your
  24. normal variables. Strings that match parenthesized parts of a
  25. regular expression are saved under names containing only digits after
  26. the C<$> (see L<perlop> and L<perlre>). In addition, several special
  27. variables that provide windows into the inner working of Perl have names
  28. containing punctuation characters (see L<perlvar>).
  29. Scalar values are always named with '$', even when referring to a scalar
  30. that is part of an array. It works like the English word "the". Thus
  31. we have:
  32. $days # the simple scalar value "days"
  33. $days[28] # the 29th element of array @days
  34. $days{'Feb'} # the 'Feb' value from hash %days
  35. $#days # the last index of array @days
  36. but entire arrays or array slices are denoted by '@', which works much like
  37. the word "these" or "those":
  38. @days # ($days[0], $days[1],... $days[n])
  39. @days[3,4,5] # same as @days[3..5]
  40. @days{'a','c'} # same as ($days{'a'},$days{'c'})
  41. and entire hashes are denoted by '%':
  42. %days # (key1, val1, key2, val2 ...)
  43. In addition, subroutines are named with an initial '&', though this is
  44. optional when it's otherwise unambiguous (just as "do" is often
  45. redundant in English). Symbol table entries can be named with an
  46. initial '*', but you don't really care about that yet.
  47. Every variable type has its own namespace. You can, without fear of
  48. conflict, use the same name for a scalar variable, an array, or a hash
  49. (or, for that matter, a filehandle, a subroutine name, or a label).
  50. This means that $foo and @foo are two different variables. It also
  51. means that C<$foo[1]> is a part of @foo, not a part of $foo. This may
  52. seem a bit weird, but that's okay, because it is weird.
  53. Because variable and array references always start with '$', '@', or '%',
  54. the "reserved" words aren't in fact reserved with respect to variable
  55. names. (They ARE reserved with respect to labels and filehandles,
  56. however, which don't have an initial special character. You can't have
  57. a filehandle named "log", for instance. Hint: you could say
  58. C<open(LOG,'logfile')> rather than C<open(log,'logfile')>. Using uppercase
  59. filehandles also improves readability and protects you from conflict
  60. with future reserved words.) Case I<IS> significant--"FOO", "Foo", and
  61. "foo" are all different names. Names that start with a letter or
  62. underscore may also contain digits and underscores.
  63. It is possible to replace such an alphanumeric name with an expression
  64. that returns a reference to an object of that type. For a description
  65. of this, see L<perlref>.
  66. Names that start with a digit may contain only more digits. Names
  67. that do not start with a letter, underscore, or digit are limited to
  68. one character, e.g., C<$%> or C<$$>. (Most of these one character names
  69. have a predefined significance to Perl. For instance, C<$$> is the
  70. current process id.)
  71. =head2 Context
  72. The interpretation of operations and values in Perl sometimes depends
  73. on the requirements of the context around the operation or value.
  74. There are two major contexts: scalar and list. Certain operations
  75. return list values in contexts wanting a list, and scalar values
  76. otherwise. (If this is true of an operation it will be mentioned in
  77. the documentation for that operation.) In other words, Perl overloads
  78. certain operations based on whether the expected return value is
  79. singular or plural. (Some words in English work this way, like "fish"
  80. and "sheep".)
  81. In a reciprocal fashion, an operation provides either a scalar or a
  82. list context to each of its arguments. For example, if you say
  83. int( <STDIN> )
  84. the integer operation provides a scalar context for the E<lt>STDINE<gt>
  85. operator, which responds by reading one line from STDIN and passing it
  86. back to the integer operation, which will then find the integer value
  87. of that line and return that. If, on the other hand, you say
  88. sort( <STDIN> )
  89. then the sort operation provides a list context for E<lt>STDINE<gt>, which
  90. will proceed to read every line available up to the end of file, and
  91. pass that list of lines back to the sort routine, which will then
  92. sort those lines and return them as a list to whatever the context
  93. of the sort was.
  94. Assignment is a little bit special in that it uses its left argument to
  95. determine the context for the right argument. Assignment to a scalar
  96. evaluates the righthand side in a scalar context, while assignment to
  97. an array or array slice evaluates the righthand side in a list
  98. context. Assignment to a list also evaluates the righthand side in a
  99. list context.
  100. User defined subroutines may choose to care whether they are being
  101. called in a scalar or list context, but most subroutines do not
  102. need to care, because scalars are automatically interpolated into
  103. lists. See L<perlfunc/wantarray>.
  104. =head2 Scalar values
  105. All data in Perl is a scalar or an array of scalars or a hash of scalars.
  106. Scalar variables may contain various kinds of singular data, such as
  107. numbers, strings, and references. In general, conversion from one form to
  108. another is transparent. (A scalar may not contain multiple values, but
  109. may contain a reference to an array or hash containing multiple values.)
  110. Because of the automatic conversion of scalars, operations, and functions
  111. that return scalars don't need to care (and, in fact, can't care) whether
  112. the context is looking for a string or a number.
  113. Scalars aren't necessarily one thing or another. There's no place to
  114. declare a scalar variable to be of type "string", or of type "number", or
  115. type "filehandle", or anything else. Perl is a contextually polymorphic
  116. language whose scalars can be strings, numbers, or references (which
  117. includes objects). While strings and numbers are considered pretty
  118. much the same thing for nearly all purposes, references are strongly-typed
  119. uncastable pointers with builtin reference-counting and destructor
  120. invocation.
  121. A scalar value is interpreted as TRUE in the Boolean sense if it is not
  122. the null string or the number 0 (or its string equivalent, "0"). The
  123. Boolean context is just a special kind of scalar context.
  124. There are actually two varieties of null scalars: defined and
  125. undefined. Undefined null scalars are returned when there is no real
  126. value for something, such as when there was an error, or at end of
  127. file, or when you refer to an uninitialized variable or element of an
  128. array. An undefined null scalar may become defined the first time you
  129. use it as if it were defined, but prior to that you can use the
  130. defined() operator to determine whether the value is defined or not.
  131. To find out whether a given string is a valid nonzero number, it's usually
  132. enough to test it against both numeric 0 and also lexical "0" (although
  133. this will cause B<-w> noises). That's because strings that aren't
  134. numbers count as 0, just as they do in B<awk>:
  135. if ($str == 0 && $str ne "0") {
  136. warn "That doesn't look like a number";
  137. }
  138. That's usually preferable because otherwise you won't treat IEEE notations
  139. like C<NaN> or C<Infinity> properly. At other times you might prefer to
  140. use the POSIX::strtod function or a regular expression to check whether
  141. data is numeric. See L<perlre> for details on regular expressions.
  142. warn "has nondigits" if /\D/;
  143. warn "not a natural number" unless /^\d+$/; # rejects -3
  144. warn "not an integer" unless /^-?\d+$/; # rejects +3
  145. warn "not an integer" unless /^[+-]?\d+$/;
  146. warn "not a decimal number" unless /^-?\d+\.?\d*$/; # rejects .2
  147. warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
  148. warn "not a C float"
  149. unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
  150. The length of an array is a scalar value. You may find the length of
  151. array @days by evaluating C<$#days>, as in B<csh>. (Actually, it's not
  152. the length of the array, it's the subscript of the last element, because
  153. there is (ordinarily) a 0th element.) Assigning to C<$#days> changes the
  154. length of the array. Shortening an array by this method destroys
  155. intervening values. Lengthening an array that was previously shortened
  156. I<NO LONGER> recovers the values that were in those elements. (It used to
  157. in Perl 4, but we had to break this to make sure destructors were
  158. called when expected.) You can also gain some miniscule measure of efficiency by
  159. pre-extending an array that is going to get big. (You can also extend
  160. an array by assigning to an element that is off the end of the array.)
  161. You can truncate an array down to nothing by assigning the null list ()
  162. to it. The following are equivalent:
  163. @whatever = ();
  164. $#whatever = -1;
  165. If you evaluate a named array in a scalar context, it returns the length of
  166. the array. (Note that this is not true of lists, which return the
  167. last value, like the C comma operator, nor of built-in functions, which return
  168. whatever they feel like returning.) The following is always true:
  169. scalar(@whatever) == $#whatever - $[ + 1;
  170. Version 5 of Perl changed the semantics of C<$[>: files that don't set
  171. the value of C<$[> no longer need to worry about whether another
  172. file changed its value. (In other words, use of C<$[> is deprecated.)
  173. So in general you can assume that
  174. scalar(@whatever) == $#whatever + 1;
  175. Some programmers choose to use an explicit conversion so nothing's
  176. left to doubt:
  177. $element_count = scalar(@whatever);
  178. If you evaluate a hash in a scalar context, it returns a value that is
  179. true if and only if the hash contains any key/value pairs. (If there
  180. are any key/value pairs, the value returned is a string consisting of
  181. the number of used buckets and the number of allocated buckets, separated
  182. by a slash. This is pretty much useful only to find out whether Perl's
  183. (compiled in) hashing algorithm is performing poorly on your data set.
  184. For example, you stick 10,000 things in a hash, but evaluating %HASH in
  185. scalar context reveals "1/16", which means only one out of sixteen buckets
  186. has been touched, and presumably contains all 10,000 of your items. This
  187. isn't supposed to happen.)
  188. You can preallocate space for a hash by assigning to the keys() function.
  189. This rounds up the allocated bucked to the next power of two:
  190. keys(%users) = 1000; # allocate 1024 buckets
  191. =head2 Scalar value constructors
  192. Numeric literals are specified in any of the customary floating point or
  193. integer formats:
  194. 12345
  195. 12345.67
  196. .23E-10
  197. 0xffff # hex
  198. 0377 # octal
  199. 4_294_967_296 # underline for legibility
  200. String literals are usually delimited by either single or double
  201. quotes. They work much like shell quotes: double-quoted string
  202. literals are subject to backslash and variable substitution;
  203. single-quoted strings are not (except for "C<\'>" and "C<\\>").
  204. The usual Unix backslash rules apply for making characters such as
  205. newline, tab, etc., as well as some more exotic forms. See
  206. L<perlop/"Quote and Quotelike Operators"> for a list.
  207. Octal or hex representations in string literals (e.g. '0xffff') are not
  208. automatically converted to their integer representation. The hex() and
  209. oct() functions make these conversions for you. See L<perlfunc/hex> and
  210. L<perlfunc/oct> for more details.
  211. You can also embed newlines directly in your strings, i.e., they can end
  212. on a different line than they begin. This is nice, but if you forget
  213. your trailing quote, the error will not be reported until Perl finds
  214. another line containing the quote character, which may be much further
  215. on in the script. Variable substitution inside strings is limited to
  216. scalar variables, arrays, and array slices. (In other words,
  217. names beginning with $ or @, followed by an optional bracketed
  218. expression as a subscript.) The following code segment prints out "The
  219. price is $Z<>100."
  220. $Price = '$100'; # not interpreted
  221. print "The price is $Price.\n"; # interpreted
  222. As in some shells, you can put curly brackets around the name to
  223. delimit it from following alphanumerics. In fact, an identifier
  224. within such curlies is forced to be a string, as is any single
  225. identifier within a hash subscript. Our earlier example,
  226. $days{'Feb'}
  227. can be written as
  228. $days{Feb}
  229. and the quotes will be assumed automatically. But anything more complicated
  230. in the subscript will be interpreted as an expression.
  231. Note that a
  232. single-quoted string must be separated from a preceding word by a
  233. space, because single quote is a valid (though deprecated) character in
  234. a variable name (see L<perlmod/Packages>).
  235. Three special literals are __FILE__, __LINE__, and __PACKAGE__, which
  236. represent the current filename, line number, and package name at that
  237. point in your program. They may be used only as separate tokens; they
  238. will not be interpolated into strings. If there is no current package
  239. (due to an empty C<package;> directive), __PACKAGE__ is the undefined value.
  240. The tokens __END__ and __DATA__ may be used to indicate the logical end
  241. of the script before the actual end of file. Any following text is
  242. ignored, but may be read via a DATA filehandle: main::DATA for __END__,
  243. or PACKNAME::DATA (where PACKNAME is the current package) for __DATA__.
  244. The two control characters ^D and ^Z are synonyms for __END__ (or
  245. __DATA__ in a module). See L<SelfLoader> for more description of
  246. __DATA__, and an example of its use. Note that you cannot read from the
  247. DATA filehandle in a BEGIN block: the BEGIN block is executed as soon as
  248. it is seen (during compilation), at which point the corresponding
  249. __DATA__ (or __END__) token has not yet been seen.
  250. A word that has no other interpretation in the grammar will
  251. be treated as if it were a quoted string. These are known as
  252. "barewords". As with filehandles and labels, a bareword that consists
  253. entirely of lowercase letters risks conflict with future reserved
  254. words, and if you use the B<-w> switch, Perl will warn you about any
  255. such words. Some people may wish to outlaw barewords entirely. If you
  256. say
  257. use strict 'subs';
  258. then any bareword that would NOT be interpreted as a subroutine call
  259. produces a compile-time error instead. The restriction lasts to the
  260. end of the enclosing block. An inner block may countermand this
  261. by saying C<no strict 'subs'>.
  262. Array variables are interpolated into double-quoted strings by joining all
  263. the elements of the array with the delimiter specified in the C<$">
  264. variable (C<$LIST_SEPARATOR> in English), space by default. The following
  265. are equivalent:
  266. $temp = join($",@ARGV);
  267. system "echo $temp";
  268. system "echo @ARGV";
  269. Within search patterns (which also undergo double-quotish substitution)
  270. there is a bad ambiguity: Is C</$foo[bar]/> to be interpreted as
  271. C</${foo}[bar]/> (where C<[bar]> is a character class for the regular
  272. expression) or as C</${foo[bar]}/> (where C<[bar]> is the subscript to array
  273. @foo)? If @foo doesn't otherwise exist, then it's obviously a
  274. character class. If @foo exists, Perl takes a good guess about C<[bar]>,
  275. and is almost always right. If it does guess wrong, or if you're just
  276. plain paranoid, you can force the correct interpretation with curly
  277. brackets as above.
  278. A line-oriented form of quoting is based on the shell "here-doc"
  279. syntax. Following a C<E<lt>E<lt>> you specify a string to terminate
  280. the quoted material, and all lines following the current line down to
  281. the terminating string are the value of the item. The terminating
  282. string may be either an identifier (a word), or some quoted text. If
  283. quoted, the type of quotes you use determines the treatment of the
  284. text, just as in regular quoting. An unquoted identifier works like
  285. double quotes. There must be no space between the C<E<lt>E<lt>> and
  286. the identifier. (If you put a space it will be treated as a null
  287. identifier, which is valid, and matches the first empty line.) The
  288. terminating string must appear by itself (unquoted and with no
  289. surrounding whitespace) on the terminating line.
  290. print <<EOF;
  291. The price is $Price.
  292. EOF
  293. print <<"EOF"; # same as above
  294. The price is $Price.
  295. EOF
  296. print <<`EOC`; # execute commands
  297. echo hi there
  298. echo lo there
  299. EOC
  300. print <<"foo", <<"bar"; # you can stack them
  301. I said foo.
  302. foo
  303. I said bar.
  304. bar
  305. myfunc(<<"THIS", 23, <<'THAT');
  306. Here's a line
  307. or two.
  308. THIS
  309. and here's another.
  310. THAT
  311. Just don't forget that you have to put a semicolon on the end
  312. to finish the statement, as Perl doesn't know you're not going to
  313. try to do this:
  314. print <<ABC
  315. 179231
  316. ABC
  317. + 20;
  318. =head2 List value constructors
  319. List values are denoted by separating individual values by commas
  320. (and enclosing the list in parentheses where precedence requires it):
  321. (LIST)
  322. In a context not requiring a list value, the value of the list
  323. literal is the value of the final element, as with the C comma operator.
  324. For example,
  325. @foo = ('cc', '-E', $bar);
  326. assigns the entire list value to array foo, but
  327. $foo = ('cc', '-E', $bar);
  328. assigns the value of variable bar to variable foo. Note that the value
  329. of an actual array in a scalar context is the length of the array; the
  330. following assigns the value 3 to $foo:
  331. @foo = ('cc', '-E', $bar);
  332. $foo = @foo; # $foo gets 3
  333. You may have an optional comma before the closing parenthesis of a
  334. list literal, so that you can say:
  335. @foo = (
  336. 1,
  337. 2,
  338. 3,
  339. );
  340. LISTs do automatic interpolation of sublists. That is, when a LIST is
  341. evaluated, each element of the list is evaluated in a list context, and
  342. the resulting list value is interpolated into LIST just as if each
  343. individual element were a member of LIST. Thus arrays and hashes lose their
  344. identity in a LIST--the list
  345. (@foo,@bar,&SomeSub,%glarch)
  346. contains all the elements of @foo followed by all the elements of @bar,
  347. followed by all the elements returned by the subroutine named SomeSub
  348. called in a list context, followed by the key/value pairs of %glarch.
  349. To make a list reference that does I<NOT> interpolate, see L<perlref>.
  350. The null list is represented by (). Interpolating it in a list
  351. has no effect. Thus ((),(),()) is equivalent to (). Similarly,
  352. interpolating an array with no elements is the same as if no
  353. array had been interpolated at that point.
  354. A list value may also be subscripted like a normal array. You must
  355. put the list in parentheses to avoid ambiguity. For example:
  356. # Stat returns list value.
  357. $time = (stat($file))[8];
  358. # SYNTAX ERROR HERE.
  359. $time = stat($file)[8]; # OOPS, FORGOT PARENTHESES
  360. # Find a hex digit.
  361. $hexdigit = ('a','b','c','d','e','f')[$digit-10];
  362. # A "reverse comma operator".
  363. return (pop(@foo),pop(@foo))[0];
  364. You may assign to C<undef> in a list. This is useful for throwing
  365. away some of the return values of a function:
  366. ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
  367. Lists may be assigned to if and only if each element of the list
  368. is legal to assign to:
  369. ($a, $b, $c) = (1, 2, 3);
  370. ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  371. List assignment in a scalar context returns the number of elements
  372. produced by the expression on the right side of the assignment:
  373. $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
  374. $x = (($foo,$bar) = f()); # set $x to f()'s return count
  375. This is very handy when you want to do a list assignment in a Boolean
  376. context, because most list functions return a null list when finished,
  377. which when assigned produces a 0, which is interpreted as FALSE.
  378. The final element may be an array or a hash:
  379. ($a, $b, @rest) = split;
  380. my($a, $b, %rest) = @_;
  381. You can actually put an array or hash anywhere in the list, but the first one
  382. in the list will soak up all the values, and anything after it will get
  383. a null value. This may be useful in a local() or my().
  384. A hash literal contains pairs of values to be interpreted
  385. as a key and a value:
  386. # same as map assignment above
  387. %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  388. While literal lists and named arrays are usually interchangeable, that's
  389. not the case for hashes. Just because you can subscript a list value like
  390. a normal array does not mean that you can subscript a list value as a
  391. hash. Likewise, hashes included as parts of other lists (including
  392. parameters lists and return lists from functions) always flatten out into
  393. key/value pairs. That's why it's good to use references sometimes.
  394. It is often more readable to use the C<=E<gt>> operator between key/value
  395. pairs. The C<=E<gt>> operator is mostly just a more visually distinctive
  396. synonym for a comma, but it also arranges for its left-hand operand to be
  397. interpreted as a string--if it's a bareword that would be a legal identifier.
  398. This makes it nice for initializing hashes:
  399. %map = (
  400. red => 0x00f,
  401. blue => 0x0f0,
  402. green => 0xf00,
  403. );
  404. or for initializing hash references to be used as records:
  405. $rec = {
  406. witch => 'Mable the Merciless',
  407. cat => 'Fluffy the Ferocious',
  408. date => '10/31/1776',
  409. };
  410. or for using call-by-named-parameter to complicated functions:
  411. $field = $query->radio_group(
  412. name => 'group_name',
  413. values => ['eenie','meenie','minie'],
  414. default => 'meenie',
  415. linebreak => 'true',
  416. labels => \%labels
  417. );
  418. Note that just because a hash is initialized in that order doesn't
  419. mean that it comes out in that order. See L<perlfunc/sort> for examples
  420. of how to arrange for an output ordering.
  421. =head2 Typeglobs and Filehandles
  422. Perl uses an internal type called a I<typeglob> to hold an entire
  423. symbol table entry. The type prefix of a typeglob is a C<*>, because
  424. it represents all types. This used to be the preferred way to
  425. pass arrays and hashes by reference into a function, but now that
  426. we have real references, this is seldom needed.
  427. The main use of typeglobs in modern Perl is create symbol table aliases.
  428. This assignment:
  429. *this = *that;
  430. makes $this an alias for $that, @this an alias for @that, %this an alias
  431. for %that, &this an alias for &that, etc. Much safer is to use a reference.
  432. This:
  433. local *Here::blue = \$There::green;
  434. temporarily makes $Here::blue an alias for $There::green, but doesn't
  435. make @Here::blue an alias for @There::green, or %Here::blue an alias for
  436. %There::green, etc. See L<perlmod/"Symbol Tables"> for more examples
  437. of this. Strange though this may seem, this is the basis for the whole
  438. module import/export system.
  439. Another use for typeglobs is to to pass filehandles into a function or
  440. to create new filehandles. If you need to use a typeglob to save away
  441. a filehandle, do it this way:
  442. $fh = *STDOUT;
  443. or perhaps as a real reference, like this:
  444. $fh = \*STDOUT;
  445. See L<perlsub> for examples of using these as indirect filehandles
  446. in functions.
  447. Typeglobs are also a way to create a local filehandle using the local()
  448. operator. These last until their block is exited, but may be passed back.
  449. For example:
  450. sub newopen {
  451. my $path = shift;
  452. local *FH; # not my!
  453. open (FH, $path) or return undef;
  454. return *FH;
  455. }
  456. $fh = newopen('/etc/passwd');
  457. Now that we have the *foo{THING} notation, typeglobs aren't used as much
  458. for filehandle manipulations, although they're still needed to pass brand
  459. new file and directory handles into or out of functions. That's because
  460. *HANDLE{IO} only works if HANDLE has already been used as a handle.
  461. In other words, *FH can be used to create new symbol table entries,
  462. but *foo{THING} cannot.
  463. Another way to create anonymous filehandles is with the IO::Handle
  464. module and its ilk. These modules have the advantage of not hiding
  465. different types of the same name during the local(). See the bottom of
  466. L<perlfunc/open()> for an example.
  467. See L<perlref>, L<perlsub>, and L<perlmod/"Symbol Tables"> for more
  468. discussion on typeglobs and the *foo{THING} syntax.