Install Perl 5.8.8
[msysgit.git] / mingw / html / pod / perldata.html
blobeb0bcb137c9b43b1a534e3d17f41e2d0dee3e91e
1 <?xml version="1.0" ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <title>perldata - Perl data types</title>
6 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
7 <link rev="made" href="mailto:" />
8 </head>
10 <body style="background-color: white">
11 <table border="0" width="100%" cellspacing="0" cellpadding="3">
12 <tr><td class="block" style="background-color: #cccccc" valign="middle">
13 <big><strong><span class="block">&nbsp;perldata - Perl data types</span></strong></big>
14 </td></tr>
15 </table>
17 <p><a name="__index__"></a></p>
18 <!-- INDEX BEGIN -->
20 <ul>
22 <li><a href="#name">NAME</a></li>
23 <li><a href="#description">DESCRIPTION</a></li>
24 <ul>
26 <li><a href="#variable_names">Variable names</a></li>
27 <li><a href="#context">Context</a></li>
28 <li><a href="#scalar_values">Scalar values</a></li>
29 <li><a href="#scalar_value_constructors">Scalar value constructors</a></li>
30 <ul>
32 <li><a href="#version_strings">Version Strings</a></li>
33 <li><a href="#special_literals">Special Literals</a></li>
34 <li><a href="#barewords">Barewords</a></li>
35 <li><a href="#array_joining_delimiter">Array Joining Delimiter</a></li>
36 </ul>
38 <li><a href="#list_value_constructors">List value constructors</a></li>
39 <li><a href="#subscripts">Subscripts</a></li>
40 <li><a href="#slices">Slices</a></li>
41 <li><a href="#typeglobs_and_filehandles">Typeglobs and Filehandles</a></li>
42 </ul>
44 <li><a href="#see_also">SEE ALSO</a></li>
45 </ul>
46 <!-- INDEX END -->
48 <hr />
49 <p>
50 </p>
51 <h1><a name="name">NAME</a></h1>
52 <p>perldata - Perl data types</p>
53 <p>
54 </p>
55 <hr />
56 <h1><a name="description">DESCRIPTION</a></h1>
57 <p>
58 </p>
59 <h2><a name="variable_names_x_variable__name__x_variable_name__x_data_type__x_type_">Variable names
60 </a></h2>
61 <p>Perl has three built-in data types: scalars, arrays of scalars, and
62 associative arrays of scalars, known as ``hashes''. A scalar is a
63 single string (of any size, limited only by the available memory),
64 number, or a reference to something (which will be discussed
65 in <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a>). Normal arrays are ordered lists of scalars indexed
66 by number, starting with 0. Hashes are unordered collections of scalar
67 values indexed by their associated string key.</p>
68 <p>Values are usually referred to by name, or through a named reference.
69 The first character of the name tells you to what sort of data
70 structure it refers. The rest of the name tells you the particular
71 value to which it refers. Usually this name is a single <em>identifier</em>,
72 that is, a string beginning with a letter or underscore, and
73 containing letters, underscores, and digits. In some cases, it may
74 be a chain of identifiers, separated by <code>::</code> (or by the slightly
75 archaic <code>'</code>); all but the last are interpreted as names of packages,
76 to locate the namespace in which to look up the final identifier
77 (see <a href="file://C|\msysgit\mingw\html/pod/perlmod.html#packages">Packages in the perlmod manpage</a> for details). It's possible to substitute
78 for a simple identifier, an expression that produces a reference
79 to the value at runtime. This is described in more detail below
80 and in <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a>.
81 </p>
82 <p>Perl also has its own built-in variables whose names don't follow
83 these rules. They have strange names so they don't accidentally
84 collide with one of your normal variables. Strings that match
85 parenthesized parts of a regular expression are saved under names
86 containing only digits after the <code>$</code> (see <a href="file://C|\msysgit\mingw\html/pod/perlop.html">the perlop manpage</a> and <a href="file://C|\msysgit\mingw\html/pod/perlre.html">the perlre manpage</a>).
87 In addition, several special variables that provide windows into
88 the inner working of Perl have names containing punctuation characters
89 and control characters. These are documented in <a href="file://C|\msysgit\mingw\html/pod/perlvar.html">the perlvar manpage</a>.
90 </p>
91 <p>Scalar values are always named with '$', even when referring to a
92 scalar that is part of an array or a hash. The '$' symbol works
93 semantically like the English word ``the'' in that it indicates a
94 single value is expected.
95 </p>
96 <pre>
97 $days # the simple scalar value &quot;days&quot;
98 $days[28] # the 29th element of array @days
99 $days{'Feb'} # the 'Feb' value from hash %days
100 $#days # the last index of array @days</pre>
101 <p>Entire arrays (and slices of arrays and hashes) are denoted by '@',
102 which works much like the word ``these'' or ``those'' does in English,
103 in that it indicates multiple values are expected.
104 </p>
105 <pre>
106 @days # ($days[0], $days[1],... $days[n])
107 @days[3,4,5] # same as ($days[3],$days[4],$days[5])
108 @days{'a','c'} # same as ($days{'a'},$days{'c'})</pre>
109 <p>Entire hashes are denoted by '%':
110 </p>
111 <pre>
112 %days # (key1, val1, key2, val2 ...)</pre>
113 <p>In addition, subroutines are named with an initial '&amp;', though this
114 is optional when unambiguous, just as the word ``do'' is often redundant
115 in English. Symbol table entries can be named with an initial '*',
116 but you don't really care about that yet (if ever :-).</p>
117 <p>Every variable type has its own namespace, as do several
118 non-variable identifiers. This means that you can, without fear
119 of conflict, use the same name for a scalar variable, an array, or
120 a hash--or, for that matter, for a filehandle, a directory handle, a
121 subroutine name, a format name, or a label. This means that $foo
122 and @foo are two different variables. It also means that <code>$foo[1]</code>
123 is a part of @foo, not a part of $foo. This may seem a bit weird,
124 but that's okay, because it is weird.
125 </p>
126 <p>Because variable references always start with '$', '@', or '%', the
127 ``reserved'' words aren't in fact reserved with respect to variable
128 names. They <em>are</em> reserved with respect to labels and filehandles,
129 however, which don't have an initial special character. You can't
130 have a filehandle named ``log'', for instance. Hint: you could say
131 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>open(LOG,'logfile')</code></a> rather than <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>open(log,'logfile')</code></a>. Using
132 uppercase filehandles also improves readability and protects you
133 from conflict with future reserved words. Case <em>is</em> significant--``FOO'',
134 ``Foo'', and ``foo'' are all different names. Names that start with a
135 letter or underscore may also contain digits and underscores.
137 </p>
138 <p>It is possible to replace such an alphanumeric name with an expression
139 that returns a reference to the appropriate type. For a description
140 of this, see <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a>.</p>
141 <p>Names that start with a digit may contain only more digits. Names
142 that do not start with a letter, underscore, digit or a caret (i.e.
143 a control character) are limited to one character, e.g., <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$%</code></a> or
144 <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$$</code></a>. (Most of these one character names have a predefined
145 significance to Perl. For instance, <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$$</code></a> is the current process
146 id.)</p>
148 </p>
149 <h2><a name="context_x_context__x_scalar_context__x_list_context_">Context
150 </a></h2>
151 <p>The interpretation of operations and values in Perl sometimes depends
152 on the requirements of the context around the operation or value.
153 There are two major contexts: list and scalar. Certain operations
154 return list values in contexts wanting a list, and scalar values
155 otherwise. If this is true of an operation it will be mentioned in
156 the documentation for that operation. In other words, Perl overloads
157 certain operations based on whether the expected return value is
158 singular or plural. Some words in English work this way, like ``fish''
159 and ``sheep''.</p>
160 <p>In a reciprocal fashion, an operation provides either a scalar or a
161 list context to each of its arguments. For example, if you say</p>
162 <pre>
163 int( &lt;STDIN&gt; )</pre>
164 <p>the integer operation provides scalar context for the &lt;&gt;
165 operator, which responds by reading one line from STDIN and passing it
166 back to the integer operation, which will then find the integer value
167 of that line and return that. If, on the other hand, you say</p>
168 <pre>
169 sort( &lt;STDIN&gt; )</pre>
170 <p>then the sort operation provides list context for &lt;&gt;, which
171 will proceed to read every line available up to the end of file, and
172 pass that list of lines back to the sort routine, which will then
173 sort those lines and return them as a list to whatever the context
174 of the sort was.</p>
175 <p>Assignment is a little bit special in that it uses its left argument
176 to determine the context for the right argument. Assignment to a
177 scalar evaluates the right-hand side in scalar context, while
178 assignment to an array or hash evaluates the righthand side in list
179 context. Assignment to a list (or slice, which is just a list
180 anyway) also evaluates the righthand side in list context.</p>
181 <p>When you use the <code>use warnings</code> pragma or Perl's <strong>-w</strong> command-line
182 option, you may see warnings
183 about useless uses of constants or functions in ``void context''.
184 Void context just means the value has been discarded, such as a
185 statement containing only <code>&quot;fred&quot;;</code> or <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_getpwuid"><code>getpwuid(0);</code></a>. It still
186 counts as scalar context for functions that care whether or not
187 they're being called in list context.</p>
188 <p>User-defined subroutines may choose to care whether they are being
189 called in a void, scalar, or list context. Most subroutines do not
190 need to bother, though. That's because both scalars and lists are
191 automatically interpolated into lists. See <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#wantarray">wantarray in the perlfunc manpage</a>
192 for how you would dynamically discern your function's calling
193 context.</p>
195 </p>
196 <h2><a name="scalar_values_x_scalar__x_number__x_string__x_reference_">Scalar values
197 </a></h2>
198 <p>All data in Perl is a scalar, an array of scalars, or a hash of
199 scalars. A scalar may contain one single value in any of three
200 different flavors: a number, a string, or a reference. In general,
201 conversion from one form to another is transparent. Although a
202 scalar may not directly hold multiple values, it may contain a
203 reference to an array or hash which in turn contains multiple values.</p>
204 <p>Scalars aren't necessarily one thing or another. There's no place
205 to declare a scalar variable to be of type ``string'', type ``number'',
206 type ``reference'', or anything else. Because of the automatic
207 conversion of scalars, operations that return scalars don't need
208 to care (and in fact, cannot care) whether their caller is looking
209 for a string, a number, or a reference. Perl is a contextually
210 polymorphic language whose scalars can be strings, numbers, or
211 references (which includes objects). Although strings and numbers
212 are considered pretty much the same thing for nearly all purposes,
213 references are strongly-typed, uncastable pointers with builtin
214 reference-counting and destructor invocation.</p>
215 <p>A scalar value is interpreted as TRUE in the Boolean sense if it is not
216 the null string or the number 0 (or its string equivalent, ``0''). The
217 Boolean context is just a special kind of scalar context where no
218 conversion to a string or a number is ever performed.
219 </p>
220 <p>There are actually two varieties of null strings (sometimes referred
221 to as ``empty'' strings), a defined one and an undefined one. The
222 defined version is just a string of length zero, such as <code>&quot;&quot;</code>.
223 The undefined version is the value that indicates that there is
224 no real value for something, such as when there was an error, or
225 at end of file, or when you refer to an uninitialized variable or
226 element of an array or hash. Although in early versions of Perl,
227 an undefined scalar could become defined when first used in a
228 place expecting a defined value, this no longer happens except for
229 rare cases of autovivification as explained in <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a>. You can
230 use the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_defined"><code>defined()</code></a> operator to determine whether a scalar value is
231 defined (this has no meaning on arrays or hashes), and the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_undef"><code>undef()</code></a>
232 operator to produce an undefined value.
233 </p>
234 <p>To find out whether a given string is a valid non-zero number, it's
235 sometimes enough to test it against both numeric 0 and also lexical
236 ``0'' (although this will cause noises if warnings are on). That's
237 because strings that aren't numbers count as 0, just as they do in <strong>awk</strong>:</p>
238 <pre>
239 if ($str == 0 &amp;&amp; $str ne &quot;0&quot;) {
240 warn &quot;That doesn't look like a number&quot;;
241 }</pre>
242 <p>That method may be best because otherwise you won't treat IEEE
243 notations like <code>NaN</code> or <code>Infinity</code> properly. At other times, you
244 might prefer to determine whether string data can be used numerically
245 by calling the POSIX::strtod() function or by inspecting your string
246 with a regular expression (as documented in <a href="file://C|\msysgit\mingw\html/pod/perlre.html">the perlre manpage</a>).</p>
247 <pre>
248 warn &quot;has nondigits&quot; if /\D/;
249 warn &quot;not a natural number&quot; unless /^\d+$/; # rejects -3
250 warn &quot;not an integer&quot; unless /^-?\d+$/; # rejects +3
251 warn &quot;not an integer&quot; unless /^[+-]?\d+$/;
252 warn &quot;not a decimal number&quot; unless /^-?\d+\.?\d*$/; # rejects .2
253 warn &quot;not a decimal number&quot; unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
254 warn &quot;not a C float&quot;
255 unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;</pre>
256 <p>The length of an array is a scalar value. You may find the length
257 of array @days by evaluating <code>$#days</code>, as in <strong>csh</strong>. However, this
258 isn't the length of the array; it's the subscript of the last element,
259 which is a different value since there is ordinarily a 0th element.
260 Assigning to <code>$#days</code> actually changes the length of the array.
261 Shortening an array this way destroys intervening values. Lengthening
262 an array that was previously shortened does not recover values
263 that were in those elements. (It used to do so in Perl 4, but we
264 had to break this to make sure destructors were called when expected.)
265 </p>
266 <p>You can also gain some minuscule measure of efficiency by pre-extending
267 an array that is going to get big. You can also extend an array
268 by assigning to an element that is off the end of the array. You
269 can truncate an array down to nothing by assigning the null list
270 () to it. The following are equivalent:</p>
271 <pre>
272 @whatever = ();
273 $#whatever = -1;</pre>
274 <p>If you evaluate an array in scalar context, it returns the length
275 of the array. (Note that this is not true of lists, which return
276 the last value, like the C comma operator, nor of built-in functions,
277 which return whatever they feel like returning.) The following is
278 always true:
279 </p>
280 <pre>
281 scalar(@whatever) == $#whatever - $[ + 1;</pre>
282 <p>Version 5 of Perl changed the semantics of <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$[</code></a>: files that don't set
283 the value of <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$[</code></a> no longer need to worry about whether another
284 file changed its value. (In other words, use of <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$[</code></a> is deprecated.)
285 So in general you can assume that
286 </p>
287 <pre>
288 scalar(@whatever) == $#whatever + 1;</pre>
289 <p>Some programmers choose to use an explicit conversion so as to
290 leave nothing to doubt:</p>
291 <pre>
292 $element_count = scalar(@whatever);</pre>
293 <p>If you evaluate a hash in scalar context, it returns false if the
294 hash is empty. If there are any key/value pairs, it returns true;
295 more precisely, the value returned is a string consisting of the
296 number of used buckets and the number of allocated buckets, separated
297 by a slash. This is pretty much useful only to find out whether
298 Perl's internal hashing algorithm is performing poorly on your data
299 set. For example, you stick 10,000 things in a hash, but evaluating
300 %HASH in scalar context reveals <code>&quot;1/16&quot;</code>, which means only one out
301 of sixteen buckets has been touched, and presumably contains all
302 10,000 of your items. This isn't supposed to happen.
303 </p>
304 <p>You can preallocate space for a hash by assigning to the <code>keys()</code> function.
305 This rounds up the allocated buckets to the next power of two:</p>
306 <pre>
307 keys(%users) = 1000; # allocate 1024 buckets</pre>
309 </p>
310 <h2><a name="scalar_value_constructors_x_scalar__literal__x_scalar__constant_">Scalar value constructors
311 </a></h2>
312 <p>Numeric literals are specified in any of the following floating point or
313 integer formats:</p>
314 <pre>
315 12345
316 12345.67
317 .23E-10 # a very small number
318 3.14_15_92 # a very important number
319 4_294_967_296 # underscore for legibility
320 0xff # hex
321 0xdead_beef # more hex
322 0377 # octal (only numbers, begins with 0)
323 0b011011 # binary</pre>
324 <p>You are allowed to use underscores (underbars) in numeric literals
325 between digits for legibility. You could, for example, group binary
326 digits by threes (as for a Unix-style mode argument such as 0b110_100_100)
327 or by fours (to represent nibbles, as in 0b1010_0110) or in other groups.
328 </p>
329 <p>String literals are usually delimited by either single or double
330 quotes. They work much like quotes in the standard Unix shells:
331 double-quoted string literals are subject to backslash and variable
332 substitution; single-quoted strings are not (except for <code>\'</code> and
333 <code>\\</code>). The usual C-style backslash rules apply for making
334 characters such as newline, tab, etc., as well as some more exotic
335 forms. See <a href="file://C|\msysgit\mingw\html/pod/perlop.html#quote_and_quotelike_operators">Quote and Quote-like Operators in the perlop manpage</a> for a list.
336 </p>
337 <p>Hexadecimal, octal, or binary, representations in string literals
338 (e.g. '0xff') are not automatically converted to their integer
339 representation. The <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_hex"><code>hex()</code></a> and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_oct"><code>oct()</code></a> functions make these conversions
340 for you. See <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_hex">hex in the perlfunc manpage</a> and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_oct">oct in the perlfunc manpage</a> for more details.</p>
341 <p>You can also embed newlines directly in your strings, i.e., they can end
342 on a different line than they begin. This is nice, but if you forget
343 your trailing quote, the error will not be reported until Perl finds
344 another line containing the quote character, which may be much further
345 on in the script. Variable substitution inside strings is limited to
346 scalar variables, arrays, and array or hash slices. (In other words,
347 names beginning with $ or @, followed by an optional bracketed
348 expression as a subscript.) The following code segment prints out ``The
349 price is $100.''
350 </p>
351 <pre>
352 $Price = '$100'; # not interpolated
353 print &quot;The price is $Price.\n&quot;; # interpolated</pre>
354 <p>There is no double interpolation in Perl, so the <code>$100</code> is left as is.</p>
355 <p>As in some shells, you can enclose the variable name in braces to
356 disambiguate it from following alphanumerics (and underscores).
357 You must also do
358 this when interpolating a variable into a string to separate the
359 variable name from a following double-colon or an apostrophe, since
360 these would be otherwise treated as a package separator:
361 </p>
362 <pre>
363 $who = &quot;Larry&quot;;
364 print PASSWD &quot;${who}::0:0:Superuser:/:/bin/perl\n&quot;;
365 print &quot;We use ${who}speak when ${who}'s here.\n&quot;;</pre>
366 <p>Without the braces, Perl would have looked for a $whospeak, a
367 <code>$who::0</code>, and a <code>$who's</code> variable. The last two would be the
368 $0 and the $s variables in the (presumably) non-existent package
369 <code>who</code>.</p>
370 <p>In fact, an identifier within such curlies is forced to be a string,
371 as is any simple identifier within a hash subscript. Neither need
372 quoting. Our earlier example, <code>$days{'Feb'}</code> can be written as
373 <code>$days{Feb}</code> and the quotes will be assumed automatically. But
374 anything more complicated in the subscript will be interpreted as an
375 expression. This means for example that <code>$version{2.0}++</code> is
376 equivalent to <code>$version{2}++</code>, not to <code>$version{'2.0'}++</code>.</p>
378 </p>
379 <h3><a name="version_strings_x_version_string__x_vstring__x_vstring_">Version Strings
380 </a></h3>
381 <p><strong>Note:</strong> Version Strings (v-strings) have been deprecated. They will
382 not be available after Perl 5.8. The marginal benefits of v-strings
383 were greatly outweighed by the potential for Surprise and Confusion.</p>
384 <p>A literal of the form <code>v1.20.300.4000</code> is parsed as a string composed
385 of characters with the specified ordinals. This form, known as
386 v-strings, provides an alternative, more readable way to construct
387 strings, rather than use the somewhat less readable interpolation form
388 <code>&quot;\x{1}\x{14}\x{12c}\x{fa0}&quot;</code>. This is useful for representing
389 Unicode strings, and for comparing version ``numbers'' using the string
390 comparison operators, <code>cmp</code>, <code>gt</code>, <code>lt</code> etc. If there are two or
391 more dots in the literal, the leading <code>v</code> may be omitted.</p>
392 <pre>
393 print v9786; # prints UTF-8 encoded SMILEY, &quot;\x{263a}&quot;
394 print v102.111.111; # prints &quot;foo&quot;
395 print 102.111.111; # same</pre>
396 <p>Such literals are accepted by both <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_require"><code>require</code></a> and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_use"><code>use</code></a> for
397 doing a version check. The <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___v"><code>$^V</code></a> special variable also contains the
398 running Perl interpreter's version in this form. See <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___v">$^V in the perlvar manpage</a>.
399 Note that using the v-strings for IPv4 addresses is not portable unless
400 you also use the <code>inet_aton()/inet_ntoa()</code> routines of the Socket package.</p>
401 <p>Note that since Perl 5.8.1 the single-number v-strings (like <code>v65</code>)
402 are not v-strings before the <code>=&gt;</code> operator (which is usually used
403 to separate a hash key from a hash value), instead they are interpreted
404 as literal strings ('v65'). They were v-strings from Perl 5.6.0 to
405 Perl 5.8.0, but that caused more confusion and breakage than good.
406 Multi-number v-strings like <code>v65.66</code> and <code>65.66.67</code> continue to
407 be v-strings always.</p>
409 </p>
410 <h3><a name="special_literals_x_special_literal__x___end____x___data____x_end__x_data__x_end__x_data__x__d__x__z_">Special Literals
412 </a></h3>
413 <p>The special literals __FILE__, __LINE__, and __PACKAGE__
414 represent the current filename, line number, and package name at that
415 point in your program. They may be used only as separate tokens; they
416 will not be interpolated into strings. If there is no current package
417 (due to an empty <code>package;</code> directive), __PACKAGE__ is the undefined
418 value.
419 </p>
420 <p>The two control characters ^D and ^Z, and the tokens __END__ and __DATA__
421 may be used to indicate the logical end of the script before the actual
422 end of file. Any following text is ignored.</p>
423 <p>Text after __DATA__ but may be read via the filehandle <code>PACKNAME::DATA</code>,
424 where <code>PACKNAME</code> is the package that was current when the __DATA__
425 token was encountered. The filehandle is left open pointing to the
426 contents after __DATA__. It is the program's responsibility to
427 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_close"><code>close DATA</code></a> when it is done reading from it. For compatibility with
428 older scripts written before __DATA__ was introduced, __END__ behaves
429 like __DATA__ in the toplevel script (but not in files loaded with
430 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_require"><code>require</code></a> or <code>do</code>) and leaves the remaining contents of the
431 file accessible via <code>main::DATA</code>.</p>
432 <p>See <a href="file://C|\msysgit\mingw\html/lib/SelfLoader.html">the SelfLoader manpage</a> for more description of __DATA__, and
433 an example of its use. Note that you cannot read from the DATA
434 filehandle in a BEGIN block: the BEGIN block is executed as soon
435 as it is seen (during compilation), at which point the corresponding
436 __DATA__ (or __END__) token has not yet been seen.</p>
438 </p>
439 <h3><a name="barewords_x_bareword_">Barewords
440 </a></h3>
441 <p>A word that has no other interpretation in the grammar will
442 be treated as if it were a quoted string. These are known as
443 ``barewords''. As with filehandles and labels, a bareword that consists
444 entirely of lowercase letters risks conflict with future reserved
445 words, and if you use the <code>use warnings</code> pragma or the <strong>-w</strong> switch,
446 Perl will warn you about any
447 such words. Some people may wish to outlaw barewords entirely. If you
448 say</p>
449 <pre>
450 use strict 'subs';</pre>
451 <p>then any bareword that would NOT be interpreted as a subroutine call
452 produces a compile-time error instead. The restriction lasts to the
453 end of the enclosing block. An inner block may countermand this
454 by saying <code>no strict 'subs'</code>.</p>
456 </p>
457 <h3><a name="array_joining_delimiter_x_array__interpolation__x_interpolation__array__x___">Array Joining Delimiter
458 </a></h3>
459 <p>Arrays and slices are interpolated into double-quoted strings
460 by joining the elements with the delimiter specified in the <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item__"><code>$&quot;</code></a>
461 variable (<a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item__list_separator"><code>$LIST_SEPARATOR</code></a> if ``use English;'' is specified),
462 space by default. The following are equivalent:</p>
463 <pre>
464 $temp = join($&quot;, @ARGV);
465 system &quot;echo $temp&quot;;</pre>
466 <pre>
467 system &quot;echo @ARGV&quot;;</pre>
468 <p>Within search patterns (which also undergo double-quotish substitution)
469 there is an unfortunate ambiguity: Is <code>/$foo[bar]/</code> to be interpreted as
470 <code>/${foo}[bar]/</code> (where <code>[bar]</code> is a character class for the regular
471 expression) or as <code>/${foo[bar]}/</code> (where <code>[bar]</code> is the subscript to array
472 @foo)? If @foo doesn't otherwise exist, then it's obviously a
473 character class. If @foo exists, Perl takes a good guess about <code>[bar]</code>,
474 and is almost always right. If it does guess wrong, or if you're just
475 plain paranoid, you can force the correct interpretation with curly
476 braces as above.</p>
477 <p>If you're looking for the information on how to use here-documents,
478 which used to be here, that's been moved to
479 <a href="file://C|\msysgit\mingw\html/pod/perlop.html#quote_and_quotelike_operators">Quote and Quote-like Operators in the perlop manpage</a>.</p>
481 </p>
482 <h2><a name="list_value_constructors_x_list_">List value constructors
483 </a></h2>
484 <p>List values are denoted by separating individual values by commas
485 (and enclosing the list in parentheses where precedence requires it):</p>
486 <pre>
487 (LIST)</pre>
488 <p>In a context not requiring a list value, the value of what appears
489 to be a list literal is simply the value of the final element, as
490 with the C comma operator. For example,</p>
491 <pre>
492 @foo = ('cc', '-E', $bar);</pre>
493 <p>assigns the entire list value to array @foo, but</p>
494 <pre>
495 $foo = ('cc', '-E', $bar);</pre>
496 <p>assigns the value of variable $bar to the scalar variable $foo.
497 Note that the value of an actual array in scalar context is the
498 length of the array; the following assigns the value 3 to $foo:</p>
499 <pre>
500 @foo = ('cc', '-E', $bar);
501 $foo = @foo; # $foo gets 3</pre>
502 <p>You may have an optional comma before the closing parenthesis of a
503 list literal, so that you can say:</p>
504 <pre>
505 @foo = (
509 );</pre>
510 <p>To use a here-document to assign an array, one line per element,
511 you might use an approach like this:</p>
512 <pre>
513 @sauces = &lt;&lt;End_Lines =~ m/(\S.*\S)/g;
514 normal tomato
515 spicy tomato
516 green chile
517 pesto
518 white wine
519 End_Lines</pre>
520 <p>LISTs do automatic interpolation of sublists. That is, when a LIST is
521 evaluated, each element of the list is evaluated in list context, and
522 the resulting list value is interpolated into LIST just as if each
523 individual element were a member of LIST. Thus arrays and hashes lose their
524 identity in a LIST--the list</p>
525 <pre>
526 (@foo,@bar,&amp;SomeSub,%glarch)</pre>
527 <p>contains all the elements of @foo followed by all the elements of @bar,
528 followed by all the elements returned by the subroutine named SomeSub
529 called in list context, followed by the key/value pairs of %glarch.
530 To make a list reference that does <em>NOT</em> interpolate, see <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a>.</p>
531 <p>The null list is represented by (). Interpolating it in a list
532 has no effect. Thus ((),(),()) is equivalent to (). Similarly,
533 interpolating an array with no elements is the same as if no
534 array had been interpolated at that point.</p>
535 <p>This interpolation combines with the facts that the opening
536 and closing parentheses are optional (except when necessary for
537 precedence) and lists may end with an optional comma to mean that
538 multiple commas within lists are legal syntax. The list <code>1,,3</code> is a
539 concatenation of two lists, <code>1,</code> and <code>3</code>, the first of which ends
540 with that optional comma. <code>1,,3</code> is <code>(1,),(3)</code> is <code>1,3</code> (And
541 similarly for <code>1,,,3</code> is <code>(1,),(,),3</code> is <code>1,3</code> and so on.) Not that
542 we'd advise you to use this obfuscation.</p>
543 <p>A list value may also be subscripted like a normal array. You must
544 put the list in parentheses to avoid ambiguity. For example:</p>
545 <pre>
546 # Stat returns list value.
547 $time = (stat($file))[8];</pre>
548 <pre>
549 # SYNTAX ERROR HERE.
550 $time = stat($file)[8]; # OOPS, FORGOT PARENTHESES</pre>
551 <pre>
552 # Find a hex digit.
553 $hexdigit = ('a','b','c','d','e','f')[$digit-10];</pre>
554 <pre>
555 # A &quot;reverse comma operator&quot;.
556 return (pop(@foo),pop(@foo))[0];</pre>
557 <p>Lists may be assigned to only when each element of the list
558 is itself legal to assign to:</p>
559 <pre>
560 ($a, $b, $c) = (1, 2, 3);</pre>
561 <pre>
562 ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);</pre>
563 <p>An exception to this is that you may assign to <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_undef"><code>undef</code></a> in a list.
564 This is useful for throwing away some of the return values of a
565 function:</p>
566 <pre>
567 ($dev, $ino, undef, undef, $uid, $gid) = stat($file);</pre>
568 <p>List assignment in scalar context returns the number of elements
569 produced by the expression on the right side of the assignment:</p>
570 <pre>
571 $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
572 $x = (($foo,$bar) = f()); # set $x to f()'s return count</pre>
573 <p>This is handy when you want to do a list assignment in a Boolean
574 context, because most list functions return a null list when finished,
575 which when assigned produces a 0, which is interpreted as FALSE.</p>
576 <p>It's also the source of a useful idiom for executing a function or
577 performing an operation in list context and then counting the number of
578 return values, by assigning to an empty list and then using that
579 assignment in scalar context. For example, this code:</p>
580 <pre>
581 $count = () = $string =~ /\d+/g;</pre>
582 <p>will place into $count the number of digit groups found in $string.
583 This happens because the pattern match is in list context (since it
584 is being assigned to the empty list), and will therefore return a list
585 of all matching parts of the string. The list assignment in scalar
586 context will translate that into the number of elements (here, the
587 number of times the pattern matched) and assign that to $count. Note
588 that simply using</p>
589 <pre>
590 $count = $string =~ /\d+/g;</pre>
591 <p>would not have worked, since a pattern match in scalar context will
592 only return true or false, rather than a count of matches.</p>
593 <p>The final element of a list assignment may be an array or a hash:</p>
594 <pre>
595 ($a, $b, @rest) = split;
596 my($a, $b, %rest) = @_;</pre>
597 <p>You can actually put an array or hash anywhere in the list, but the first one
598 in the list will soak up all the values, and anything after it will become
599 undefined. This may be useful in a <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my()</code></a> or local().</p>
600 <p>A hash can be initialized using a literal list holding pairs of
601 items to be interpreted as a key and a value:</p>
602 <pre>
603 # same as map assignment above
604 %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);</pre>
605 <p>While literal lists and named arrays are often interchangeable, that's
606 not the case for hashes. Just because you can subscript a list value like
607 a normal array does not mean that you can subscript a list value as a
608 hash. Likewise, hashes included as parts of other lists (including
609 parameters lists and return lists from functions) always flatten out into
610 key/value pairs. That's why it's good to use references sometimes.</p>
611 <p>It is often more readable to use the <code>=&gt;</code> operator between key/value
612 pairs. The <code>=&gt;</code> operator is mostly just a more visually distinctive
613 synonym for a comma, but it also arranges for its left-hand operand to be
614 interpreted as a string -- if it's a bareword that would be a legal simple
615 identifier (<code>=&gt;</code> doesn't quote compound identifiers, that contain
616 double colons). This makes it nice for initializing hashes:</p>
617 <pre>
618 %map = (
619 red =&gt; 0x00f,
620 blue =&gt; 0x0f0,
621 green =&gt; 0xf00,
622 );</pre>
623 <p>or for initializing hash references to be used as records:</p>
624 <pre>
625 $rec = {
626 witch =&gt; 'Mable the Merciless',
627 cat =&gt; 'Fluffy the Ferocious',
628 date =&gt; '10/31/1776',
629 };</pre>
630 <p>or for using call-by-named-parameter to complicated functions:</p>
631 <pre>
632 $field = $query-&gt;radio_group(
633 name =&gt; 'group_name',
634 values =&gt; ['eenie','meenie','minie'],
635 default =&gt; 'meenie',
636 linebreak =&gt; 'true',
637 labels =&gt; \%labels
638 );</pre>
639 <p>Note that just because a hash is initialized in that order doesn't
640 mean that it comes out in that order. See <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_sort">sort in the perlfunc manpage</a> for examples
641 of how to arrange for an output ordering.</p>
643 </p>
644 <h2><a name="subscripts">Subscripts</a></h2>
645 <p>An array is subscripted by specifying a dollar sign (<code>$</code>), then the
646 name of the array (without the leading <code>@</code>), then the subscript inside
647 square brackets. For example:</p>
648 <pre>
649 @myarray = (5, 50, 500, 5000);
650 print &quot;Element Number 2 is&quot;, $myarray[2], &quot;\n&quot;;</pre>
651 <p>The array indices start with 0. A negative subscript retrieves its
652 value from the end. In our example, <code>$myarray[-1]</code> would have been
653 5000, and <code>$myarray[-2]</code> would have been 500.</p>
654 <p>Hash subscripts are similar, only instead of square brackets curly brackets
655 are used. For example:</p>
656 <pre>
657 %scientists =
659 &quot;Newton&quot; =&gt; &quot;Isaac&quot;,
660 &quot;Einstein&quot; =&gt; &quot;Albert&quot;,
661 &quot;Darwin&quot; =&gt; &quot;Charles&quot;,
662 &quot;Feynman&quot; =&gt; &quot;Richard&quot;,
663 );</pre>
664 <pre>
665 print &quot;Darwin's First Name is &quot;, $scientists{&quot;Darwin&quot;}, &quot;\n&quot;;</pre>
667 </p>
668 <h2><a name="slices_x_slice__x_array__slice__x_hash__slice_">Slices
669 </a></h2>
670 <p>A common way to access an array or a hash is one scalar element at a
671 time. You can also subscript a list to get a single element from it.</p>
672 <pre>
673 $whoami = $ENV{&quot;USER&quot;}; # one element from the hash
674 $parent = $ISA[0]; # one element from the array
675 $dir = (getpwnam(&quot;daemon&quot;))[7]; # likewise, but with list</pre>
676 <p>A slice accesses several elements of a list, an array, or a hash
677 simultaneously using a list of subscripts. It's more convenient
678 than writing out the individual elements as a list of separate
679 scalar values.</p>
680 <pre>
681 ($him, $her) = @folks[0,-1]; # array slice
682 @them = @folks[0 .. 3]; # array slice
683 ($who, $home) = @ENV{&quot;USER&quot;, &quot;HOME&quot;}; # hash slice
684 ($uid, $dir) = (getpwnam(&quot;daemon&quot;))[2,7]; # list slice</pre>
685 <p>Since you can assign to a list of variables, you can also assign to
686 an array or hash slice.</p>
687 <pre>
688 @days[3..5] = qw/Wed Thu Fri/;
689 @colors{'red','blue','green'}
690 = (0xff0000, 0x0000ff, 0x00ff00);
691 @folks[0, -1] = @folks[-1, 0];</pre>
692 <p>The previous assignments are exactly equivalent to</p>
693 <pre>
694 ($days[3], $days[4], $days[5]) = qw/Wed Thu Fri/;
695 ($colors{'red'}, $colors{'blue'}, $colors{'green'})
696 = (0xff0000, 0x0000ff, 0x00ff00);
697 ($folks[0], $folks[-1]) = ($folks[-1], $folks[0]);</pre>
698 <p>Since changing a slice changes the original array or hash that it's
699 slicing, a <code>foreach</code> construct will alter some--or even all--of the
700 values of the array or hash.</p>
701 <pre>
702 foreach (@array[ 4 .. 10 ]) { s/peter/paul/ }</pre>
703 <pre>
704 foreach (@hash{qw[key1 key2]}) {
705 s/^\s+//; # trim leading whitespace
706 s/\s+$//; # trim trailing whitespace
707 s/(\w+)/\u\L$1/g; # &quot;titlecase&quot; words
708 }</pre>
709 <p>A slice of an empty list is still an empty list. Thus:</p>
710 <pre>
711 @a = ()[1,0]; # @a has no elements
712 @b = (@a)[0,1]; # @b has no elements
713 @c = (0,1)[2,3]; # @c has no elements</pre>
714 <p>But:</p>
715 <pre>
716 @a = (1)[1,0]; # @a has two elements
717 @b = (1,undef)[1,0,2]; # @b has three elements</pre>
718 <p>This makes it easy to write loops that terminate when a null list
719 is returned:</p>
720 <pre>
721 while ( ($home, $user) = (getpwent)[7,0]) {
722 printf &quot;%-8s %s\n&quot;, $user, $home;
723 }</pre>
724 <p>As noted earlier in this document, the scalar sense of list assignment
725 is the number of elements on the right-hand side of the assignment.
726 The null list contains no elements, so when the password file is
727 exhausted, the result is 0, not 2.</p>
728 <p>If you're confused about why you use an '@' there on a hash slice
729 instead of a '%', think of it like this. The type of bracket (square
730 or curly) governs whether it's an array or a hash being looked at.
731 On the other hand, the leading symbol ('$' or '@') on the array or
732 hash indicates whether you are getting back a singular value (a
733 scalar) or a plural one (a list).</p>
735 </p>
736 <h2><a name="typeglobs_and_filehandles_x_typeglob__x_filehandle__x___">Typeglobs and Filehandles
737 </a></h2>
738 <p>Perl uses an internal type called a <em>typeglob</em> to hold an entire
739 symbol table entry. The type prefix of a typeglob is a <code>*</code>, because
740 it represents all types. This used to be the preferred way to
741 pass arrays and hashes by reference into a function, but now that
742 we have real references, this is seldom needed.</p>
743 <p>The main use of typeglobs in modern Perl is create symbol table aliases.
744 This assignment:</p>
745 <pre>
746 *this = *that;</pre>
747 <p>makes $this an alias for $that, @this an alias for @that, %this an alias
748 for %that, &amp;this an alias for &amp;that, etc. Much safer is to use a reference.
749 This:</p>
750 <pre>
751 local *Here::blue = \$There::green;</pre>
752 <p>temporarily makes $Here::blue an alias for $There::green, but doesn't
753 make @Here::blue an alias for @There::green, or %Here::blue an alias for
754 %There::green, etc. See <a href="file://C|\msysgit\mingw\html/pod/perlmod.html#symbol_tables">Symbol Tables in the perlmod manpage</a> for more examples
755 of this. Strange though this may seem, this is the basis for the whole
756 module import/export system.</p>
757 <p>Another use for typeglobs is to pass filehandles into a function or
758 to create new filehandles. If you need to use a typeglob to save away
759 a filehandle, do it this way:</p>
760 <pre>
761 $fh = *STDOUT;</pre>
762 <p>or perhaps as a real reference, like this:</p>
763 <pre>
764 $fh = \*STDOUT;</pre>
765 <p>See <a href="file://C|\msysgit\mingw\html/pod/perlsub.html">the perlsub manpage</a> for examples of using these as indirect filehandles
766 in functions.</p>
767 <p>Typeglobs are also a way to create a local filehandle using the <code>local()</code>
768 operator. These last until their block is exited, but may be passed back.
769 For example:</p>
770 <pre>
771 sub newopen {
772 my $path = shift;
773 local *FH; # not my!
774 open (FH, $path) or return undef;
775 return *FH;
777 $fh = newopen('/etc/passwd');</pre>
778 <p>Now that we have the <code>*foo{THING}</code> notation, typeglobs aren't used as much
779 for filehandle manipulations, although they're still needed to pass brand
780 new file and directory handles into or out of functions. That's because
781 <code>*HANDLE{IO}</code> only works if HANDLE has already been used as a handle.
782 In other words, <code>*FH</code> must be used to create new symbol table entries;
783 <code>*foo{THING}</code> cannot. When in doubt, use <code>*FH</code>.</p>
784 <p>All functions that are capable of creating filehandles (open(),
785 opendir(), pipe(), socketpair(), sysopen(), socket(), and <code>accept())</code>
786 automatically create an anonymous filehandle if the handle passed to
787 them is an uninitialized scalar variable. This allows the constructs
788 such as <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>open(my $fh, ...)</code></a> and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>open(local $fh,...)</code></a> to be used to
789 create filehandles that will conveniently be closed automatically when
790 the scope ends, provided there are no other references to them. This
791 largely eliminates the need for typeglobs when opening filehandles
792 that must be passed around, as in the following example:</p>
793 <pre>
794 sub myopen {
795 open my $fh, &quot;@_&quot;
796 or die &quot;Can't open '@_': $!&quot;;
797 return $fh;
798 }</pre>
799 <pre>
801 my $f = myopen(&quot;&lt;/etc/motd&quot;);
802 print &lt;$f&gt;;
803 # $f implicitly closed here
804 }</pre>
805 <p>Note that if an initialized scalar variable is used instead the
806 result is different: <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>my $fh='zzz'; open($fh, ...)</code></a> is equivalent
807 to <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>open( *{'zzz'}, ...)</code></a>.
808 <code>use strict 'refs'</code> forbids such practice.</p>
809 <p>Another way to create anonymous filehandles is with the Symbol
810 module or with the IO::Handle module and its ilk. These modules
811 have the advantage of not hiding different types of the same name
812 during the local(). See the bottom of <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open">open() in the perlfunc manpage</a> for an
813 example.</p>
815 </p>
816 <hr />
817 <h1><a name="see_also">SEE ALSO</a></h1>
818 <p>See <a href="file://C|\msysgit\mingw\html/pod/perlvar.html">the perlvar manpage</a> for a description of Perl's built-in variables and
819 a discussion of legal variable names. See <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a>, <a href="file://C|\msysgit\mingw\html/pod/perlsub.html">the perlsub manpage</a>,
820 and <a href="file://C|\msysgit\mingw\html/pod/perlmod.html#symbol_tables">Symbol Tables in the perlmod manpage</a> for more discussion on typeglobs and
821 the <code>*foo{THING}</code> syntax.</p>
822 <table border="0" width="100%" cellspacing="0" cellpadding="3">
823 <tr><td class="block" style="background-color: #cccccc" valign="middle">
824 <big><strong><span class="block">&nbsp;perldata - Perl data types</span></strong></big>
825 </td></tr>
826 </table>
828 </body>
830 </html>