home *** CD-ROM | disk | FTP | other *** search
/ RISC DISC 2 / RISC_DISC_2.iso / pd_share / utilities / cli / perl / !Perl / Manual / perldata < prev    next >
Encoding:
Text File  |  1995-04-18  |  18.0 KB  |  399 lines

  1. <!-- $RCSfile$$Revision$$Date$ -->
  2. <!-- $Log$ -->
  3. <HTML>
  4. <TITLE> PERLDATA </TITLE>
  5. <h2>NAME</h2>
  6. perldata - Perl data structures
  7. <p><h2>DESCRIPTION</h2>
  8. <h3>Variable names</h3>
  9. Perl has three data structures: scalars, arrays of scalars, and
  10. associative arrays of scalars, known as "hashes".  Normal arrays are
  11. indexed by number, starting with 0.  (Negative subscripts count from
  12. the end.)  Hash arrays are indexed by string.
  13. <p>Scalar values are always named with '$', even when referring to a scalar
  14. that is part of an array.  It works like the English word "the".  Thus
  15. we have:
  16. <p><pre>
  17.         $days           # the simple scalar value "days"
  18.         $days[28]               # the 29th element of array @days
  19.         $days{'Feb'}    # the 'Feb' value from hash %days
  20.         $#days          # the last index of array @days
  21. </pre>
  22. but entire arrays or array slices are denoted by '@', which works much like
  23. the word "these" or "those":
  24. <p><pre>
  25.         @days           # ($days[0], $days[1],... $days[n])
  26.         @days[3,4,5]    # same as @days[3..5]
  27.         @days{'a','c'}  # same as ($days{'a'},$days{'c'})
  28. </pre>
  29. and entire hashes are denoted by '%':
  30. <p><pre>
  31.         %days           # (key1, val1, key2, val2 ...)
  32. </pre>
  33. In addition, subroutines are named with an initial '&', though this is
  34. optional when it's otherwise unambiguous (just as "do" is often
  35. redundant in English).  Symbol table entries can be named with an
  36. initial '*', but you don't really care about that yet.
  37. <p>Every variable type has its own namespace.  You can, without fear of
  38. conflict, use the same name for a scalar variable, an array, or a hash
  39. (or, for that matter, a filehandle, a subroutine name, or a label).
  40. This means that $foo and @foo are two different variables.  It also
  41. means that $foo[1] is a part of @foo, not a part of $foo.  This may
  42. seem a bit weird, but that's okay, because it is weird.
  43. <p>Since variable and array references always start with '$', '@', or '%',
  44. the "reserved" words aren't in fact reserved with respect to variable
  45. names.  (They ARE reserved with respect to labels and filehandles,
  46. however, which don't have an initial special character.  You can't have
  47. a filehandle named "log", for instance.  Hint: you could say
  48. <B>open(LOG,'logfile')</B> rather than <B>open(log,'logfile')</B>.  Using uppercase
  49. filehandles also improves readability and protects you from conflict
  50. with future reserved words.)  Case <I>IS</I> significant--"FOO", "Foo" and
  51. "foo" are all different names.  Names that start with a letter or
  52. underscore may also contain digits and underscores.
  53. <p>It is possible to replace such an alphanumeric name with an expression
  54. that returns a reference to an object of that type.  For a description
  55. of this, see 
  56. <A HREF="perlref.html">
  57. the perlref manpage</A>
  58. .
  59. <p>Names that start with a digit may only contain more digits.  Names
  60. which do not start with a letter, underscore,  or digit are limited to
  61. one character, e.g.  "$%" or "$$".  (Most of these one character names
  62. have a predefined significance to Perl.  For instance, $$ is the
  63. current process id.)
  64. <p><h3>Context</h3>
  65. The interpretation of operations and values in Perl sometimes depends
  66. on the requirements of the context around the operation or value.
  67. There are two major contexts: scalar and list.  Certain operations
  68. return list values in contexts wanting a list, and scalar values
  69. otherwise.  (If this is true of an operation it will be mentioned in
  70. the documentation for that operation.)  In other words, Perl overloads
  71. certain operations based on whether the expected return value is
  72. singular or plural.  (Some words in English work this way, like "fish"
  73. and "sheep".)
  74. <p>In a reciprocal fashion, an operation provides either a scalar or a
  75. list context to each of its arguments.  For example, if you say
  76. <p><pre>
  77.         int( <STDIN> )
  78. </pre>
  79. the integer operation provides a scalar context for the <STDIN>
  80. operator, which responds by reading one line from STDIN and passing it
  81. back to the integer operation, which will then find the integer value
  82. of that line and return that.  If, on the other hand, you say
  83. <p><pre>
  84.         sort( <STDIN> )
  85. </pre>
  86. then the sort operation provides a list context for <STDIN>, which
  87. will proceed to read every line available up to the end of file, and
  88. pass that list of lines back to the sort routine, which will then
  89. sort those lines and return them as a list to whatever the context
  90. of the sort was.
  91. <p>Assignment is a little bit special in that it uses its left argument to
  92. determine the context for the right argument.  Assignment to a scalar
  93. evaluates the righthand side in a scalar context, while assignment to
  94. an array or array slice evaluates the righthand side in a list
  95. context.  Assignment to a list also evaluates the righthand side in a
  96. list context.
  97. <p>User defined subroutines may choose to care whether they are being
  98. called in a scalar or list context, but most subroutines do not
  99. need to care, because scalars are automatically interpolated into
  100. lists.  See perlfunc/wantarray.
  101. <p><h3>Scalar values</h3>
  102. Scalar variables may contain various kinds of singular data, such as
  103. numbers, strings and references.  In general, conversion from one form
  104. to another is transparent.  (A scalar may not contain multiple values,
  105. but may contain a reference to an array or hash containing multiple
  106. values.)  Because of the automatic conversion of scalars, operations and
  107. functions that return scalars don't need to care (and, in fact, can't
  108. care) whether the context is looking for a string or a number.
  109. <p>A scalar value is interpreted as TRUE in the Boolean sense if it is not
  110. the null string or the number 0 (or its string equivalent, "0").  The
  111. Boolean context is just a special kind of scalar context.
  112. <p>There are actually two varieties of null scalars: defined and
  113. undefined.  Undefined null scalars are returned when there is no real
  114. value for something, such as when there was an error, or at end of
  115. file, or when you refer to an uninitialized variable or element of an
  116. array.  An undefined null scalar may become defined the first time you
  117. use it as if it were defined, but prior to that you can use the
  118. defined() operator to determine whether the value is defined or not.
  119. <p>The length of an array is a scalar value.  You may find the length of
  120. array @days by evaluating <B>$#days</B>, as in <B>csh</B>.  (Actually, it's not
  121. the length of the array, it's the subscript of the last element, since
  122. there is (ordinarily) a 0th element.)  Assigning to <B>$#days</B> changes the
  123. length of the array.  Shortening an array by this method destroys
  124. intervening values.  Lengthening an array that was previously shortened
  125. <I>NO LONGER</I> recovers the values that were in those elements.  (It used to
  126. in Perl 4, but we had to break this make to make sure destructors were
  127. called when expected.)  You can also gain some measure of efficiency by
  128. preextending an array that is going to get big.  (You can also extend
  129. an array by assigning to an element that is off the end of the array.)
  130. You can truncate an array down to nothing by assigning the null list ()
  131. to it.  The following are equivalent:
  132. <p><pre>
  133.         @whatever = ();
  134.         $#whatever = $[ - 1;
  135. </pre>
  136. If you evaluate a named array in a scalar context, it returns the length of
  137. the array.  (Note that this is not true of lists, which return the
  138. last value, like the C comma operator.)  The following is always true:
  139. <p><pre>
  140.         scalar(@whatever) == $#whatever - $[ + 1;
  141. </pre>
  142. Version 5 of Perl changed the semantics of $[: files that don't set
  143. the value of $[ no longer need to worry about whether another
  144. file changed its value.  (In other words, use of $[ is deprecated.)
  145. So in general you can just assume that
  146. <p><pre>
  147.         scalar(@whatever) == $#whatever + 1;
  148. </pre>
  149. If you evaluate a hash in a scalar context, it returns a value which is
  150. true if and only if the hash contains any key/value pairs.  (If there
  151. are any key/value pairs, the value returned is a string consisting of
  152. the number of used buckets and the number of allocated buckets, separated
  153. by a slash.  This is pretty much only useful to find out whether Perl's
  154. (compiled in) hashing algorithm is performing poorly on your data set.
  155. For example, you stick 10,000 things in a hash, but evaluating %HASH in
  156. scalar context reveals "1/16", which means only one out of sixteen buckets
  157. has been touched, and presumably contains all 10,000 of your items.  This
  158. isn't supposed to happen.)
  159. <p><h3>Scalar value constructors</h3>
  160. Numeric literals are specified in any of the customary floating point or
  161. integer formats:
  162. <p><pre>
  163.         12345
  164.         12345.67
  165.         .23E-10
  166.         0xffff          # hex
  167.         0377            # octal
  168.         4_294_967_296   # underline for legibility
  169. </pre>
  170. String literals are delimited by either single or double quotes.  They
  171. work much like shell quotes:  double-quoted string literals are subject
  172. to backslash and variable substitution; single-quoted strings are not
  173. (except for "<B>\'</B>" and "<B>\\</B>").  The usual Unix backslash rules apply for making
  174. characters such as newline, tab, etc., as well as some more exotic
  175. forms.  See perlop/qq for a list.
  176. <p>You can also embed newlines directly in your strings, i.e. they can end
  177. on a different line than they begin.  This is nice, but if you forget
  178. your trailing quote, the error will not be reported until Perl finds
  179. another line containing the quote character, which may be much further
  180. on in the script.  Variable substitution inside strings is limited to
  181. scalar variables, arrays, and array slices.  (In other words,
  182. identifiers beginning with $ or @, followed by an optional bracketed
  183. expression as a subscript.)  The following code segment prints out "The
  184. price is $100."
  185. <p><pre>
  186.         $Price = '$100';        # not interpreted
  187.         print "The price is $Price.\n"; # interpreted
  188. </pre>
  189. As in some shells, you can put curly brackets around the identifier to
  190. delimit it from following alphanumerics.  Also note that a
  191. single-quoted string must be separated from a preceding word by a
  192. space, since single quote is a valid (though discouraged) character in
  193. an identifier (see perlmod/Packages).
  194. <p>Two special literals are __LINE__ and __FILE__, which represent the
  195. current line number and filename at that point in your program.  They
  196. may only be used as separate tokens; they will not be interpolated into
  197. strings.  In addition, the token __END__ may be used to indicate the
  198. logical end of the script before the actual end of file.  Any following
  199. text is ignored, but may be read via the DATA filehandle.  (The DATA
  200. filehandle may read data only from the main script, but not from any
  201. required file or evaluated string.)  The two control characters ^D and
  202. ^Z are synonyms for __END__.
  203. <p>A word that doesn't have any other interpretation in the grammar will
  204. be treated as if it were a quoted string.  These are known as
  205. "barewords".  As with filehandles and labels, a bareword that consists
  206. entirely of lowercase letters risks conflict with future reserved
  207. words, and if you use the 
  208. <A HREF="perlrun.html#perlrun_362">-w</A>
  209.  switch, Perl will warn you about any
  210. such words.  Some people may wish to outlaw barewords entirely.  If you
  211. say
  212. <p><pre>
  213.         use strict 'subs';
  214. </pre>
  215. then any bareword that would NOT be interpreted as a subroutine call
  216. produces a compile-time error instead.  The restriction lasts to the
  217. end of the enclosing block.  An inner block may countermand this 
  218. by saying <B>no strict 'subs'</B>.
  219. <p>Array variables are interpolated into double-quoted strings by joining all
  220. the elements of the array with the delimiter specified in the 
  221. <A HREF="perlvar.html#perlvar_403">$"</A>
  222.  
  223. variable, space by default.  The following are equivalent:
  224. <p><pre>
  225.         $temp = join($",@ARGV);
  226.         system "echo $temp";
  227. </pre>
  228. <pre>
  229.         system "echo @ARGV";
  230. </pre>
  231. Within search patterns (which also undergo double-quotish substitution)
  232. there is a bad ambiguity:  Is <B>/$foo[bar]/</B> to be interpreted as
  233. <B>/${foo}[bar]/</B> (where <B>[bar]</B> is a character class for the regular
  234. expression) or as <B>/${foo[bar]}/</B> (where <B>[bar]</B> is the subscript to array
  235. @foo)?  If @foo doesn't otherwise exist, then it's obviously a
  236. character class.  If @foo exists, Perl takes a good guess about <B>[bar]</B>,
  237. and is almost always right.  If it does guess wrong, or if you're just
  238. plain paranoid, you can force the correct interpretation with curly
  239. brackets as above.
  240. <p>A line-oriented form of quoting is based on the shell "here-doc" syntax.
  241. Following a <B><<</B> you specify a string to terminate the quoted material,
  242. and all lines following the current line down to the terminating string
  243. are the value of the item.  The terminating string may be either an
  244. identifier (a word), or some quoted text.  If quoted, the type of
  245. quotes you use determines the treatment of the text, just as in regular
  246. quoting.  An unquoted identifier works like double quotes.  There must
  247. be no space between the <B><<</B> and the identifier.  (If you put a space it
  248. will be treated as a null identifier, which is valid, and matches the
  249. first blank line--see the Merry Christmas example below.)  The terminating
  250. string must appear by itself (unquoted and with no surrounding
  251. whitespace) on the terminating line.
  252. <p><pre>
  253.         print <<EOF;      # same as above
  254.         The price is $Price.
  255.         EOF
  256. </pre>
  257. <pre>
  258.         print <<"EOF";    # same as above
  259.         The price is $Price.
  260.         EOF
  261. </pre>
  262. <pre>
  263.         print << x 10;    # Legal but discouraged.  Use <<"".
  264.         Merry Christmas!
  265. </pre>
  266. <pre>
  267.         print <<`EOC`;    # execute commands
  268.         echo hi there
  269.         echo lo there
  270.         EOC
  271. </pre>
  272. <pre>
  273.         print <<"foo", <<"bar";     # you can stack them
  274.         I said foo.
  275.         foo
  276.         I said bar.
  277.         bar
  278. </pre>
  279. <pre>
  280.         myfunc(<<"THIS", 23, <<'THAT'');
  281.         Here's a line
  282.         or two.
  283.         THIS
  284.         and here another.
  285.         THAT
  286. </pre>
  287. Just don't forget that you have to put a semicolon on the end 
  288. to finish the statement, as Perl doesn't know you're not going to 
  289. try to do this:
  290. <p><pre>
  291.         print <<ABC
  292.         179231
  293.         ABC
  294.         + 20;
  295. </pre>
  296. <h3>List value constructors</h3>
  297. List values are denoted by separating individual values by commas
  298. (and enclosing the list in parentheses where precedence requires it):
  299. <p><pre>
  300.         (LIST)
  301. </pre>
  302. In a context not requiring an list value, the value of the list
  303. literal is the value of the final element, as with the C comma operator.
  304. For example,
  305. <p><pre>
  306.         @foo = ('cc', '-E', $bar);
  307. </pre>
  308. assigns the entire list value to array foo, but
  309. <p><pre>
  310.         $foo = ('cc', '-E', $bar);
  311. </pre>
  312. assigns the value of variable bar to variable foo.  Note that the value
  313. of an actual array in a scalar context is the length of the array; the
  314. following assigns to $foo the value 3:
  315. <p><pre>
  316.         @foo = ('cc', '-E', $bar);
  317.         $foo = @foo;            # $foo gets 3
  318. </pre>
  319. You may have an optional comma before the closing parenthesis of an
  320. list literal, so that you can say:
  321. <p><pre>
  322.         @foo = (
  323.         1,
  324.         2,
  325.         3,
  326.         );
  327. </pre>
  328. LISTs do automatic interpolation of sublists.  That is, when a LIST is
  329. evaluated, each element of the list is evaluated in a list context, and
  330. the resulting list value is interpolated into LIST just as if each
  331. individual element were a member of LIST.  Thus arrays lose their
  332. identity in a LIST--the list
  333. <p><pre>
  334.         (@foo,@bar,&SomeSub)
  335. </pre>
  336. contains all the elements of @foo followed by all the elements of @bar,
  337. followed by all the elements returned by the subroutine named SomeSub.
  338. To make a list reference that does <I>NOT</I> interpolate, see 
  339. <A HREF="perlref.html">
  340. the perlref manpage</A>
  341. .
  342. <p>The null list is represented by ().  Interpolating it in a list
  343. has no effect.  Thus ((),(),()) is equivalent to ().  Similarly,
  344. interpolating an array with no elements is the same as if no
  345. array had been interpolated at that point.
  346. <p>A list value may also be subscripted like a normal array.  You must
  347. put the list in parentheses to avoid ambiguity.  Examples:
  348. <p><pre>
  349.         # Stat returns list value.
  350.         $time = (stat($file))[8];
  351. </pre>
  352. <pre>
  353.         # Find a hex digit.
  354.         $hexdigit = ('a','b','c','d','e','f')[$digit-10];
  355. </pre>
  356. <pre>
  357.         # A "reverse comma operator".
  358.         return (pop(@foo),pop(@foo))[0];
  359. </pre>
  360. Lists may be assigned to if and only if each element of the list
  361. is legal to assign to:
  362. <p><pre>
  363.         ($a, $b, $c) = (1, 2, 3);
  364. </pre>
  365. <pre>
  366.         ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  367. </pre>
  368. The final element may be an array or a hash:
  369. <p><pre>
  370.         ($a, $b, @rest) = split;
  371.         local($a, $b, %rest) = @_;
  372. </pre>
  373. You can actually put an array anywhere in the list, but the first array
  374. in the list will soak up all the values, and anything after it will get
  375. a null value.  This may be useful in a local() or my().
  376. <p>A hash literal contains pairs of values to be interpreted
  377. as a key and a value:
  378. <p><pre>
  379.         # same as map assignment above
  380.         %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  381. </pre>
  382. It is often more readable to use the <B>=></B> operator between key/value pairs
  383. (the <B>=></B> operator is actually nothing more than a more visually 
  384. distinctive synonym for a comma):
  385. <p><pre>
  386.         %map = (
  387.              'red'   => 0x00f,
  388.              'blue'  => 0x0f0,
  389.              'green' => 0xf00,
  390.            );
  391. </pre>
  392. Array assignment in a scalar context returns the number of elements
  393. produced by the expression on the right side of the assignment:
  394. <p><pre>
  395.         $x = (($foo,$bar) = (3,2,1));   # set $x to 3, not 2
  396. </pre>
  397. This is very handy when you want to do a list assignment in a Boolean
  398. context, since most list functions return a null list when finished,
  399. which when assigned produces a 0, which is interpreted as FALSE.<p>