Install Perl 5.8.8
[msysgit.git] / mingw / html / pod / perlfaq4.html
blobbb4048c6b3ab58cc25b785d5f65674f4dca93fea
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>perlfaq4 - Data Manipulation</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;perlfaq4 - Data Manipulation</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 <li><a href="#data__numbers">Data: Numbers</a></li>
25 <ul>
27 <li><a href="#why_am_i_getting_long_decimals__eg__19_9499999999999__instead_of_the_numbers_i_should_be_getting__eg__19_95_">Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?</a></li>
28 <li><a href="#why_is_int___broken">Why is <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_int"><code>int()</code></a> broken?</a></li>
29 <li><a href="#why_isn_t_my_octal_data_interpreted_correctly">Why isn't my octal data interpreted correctly?</a></li>
30 <li><a href="#does_perl_have_a_round___function_what_about_ceil___and_floor___trig_functions">Does Perl have a <code>round()</code> function? What about <code>ceil()</code> and floor()? Trig functions?</a></li>
31 <li><a href="#how_do_i_convert_between_numeric_representations_bases_radixes">How do I convert between numeric representations/bases/radixes?</a></li>
32 <li><a href="#why_doesn_t___work_the_way_i_want_it_to">Why doesn't &amp; work the way I want it to?</a></li>
33 <li><a href="#how_do_i_multiply_matrices">How do I multiply matrices?</a></li>
34 <li><a href="#how_do_i_perform_an_operation_on_a_series_of_integers">How do I perform an operation on a series of integers?</a></li>
35 <li><a href="#how_can_i_output_roman_numerals">How can I output Roman numerals?</a></li>
36 <li><a href="#why_aren_t_my_random_numbers_random">Why aren't my random numbers random?</a></li>
37 <li><a href="#how_do_i_get_a_random_number_between_x_and_y">How do I get a random number between X and Y?</a></li>
38 </ul>
40 <li><a href="#data__dates">Data: Dates</a></li>
41 <ul>
43 <li><a href="#how_do_i_find_the_day_or_week_of_the_year">How do I find the day or week of the year?</a></li>
44 <li><a href="#how_do_i_find_the_current_century_or_millennium">How do I find the current century or millennium?</a></li>
45 <li><a href="#how_can_i_compare_two_dates_and_find_the_difference">How can I compare two dates and find the difference?</a></li>
46 <li><a href="#how_can_i_take_a_string_and_turn_it_into_epoch_seconds">How can I take a string and turn it into epoch seconds?</a></li>
47 <li><a href="#how_can_i_find_the_julian_day">How can I find the Julian Day?</a></li>
48 <li><a href="#how_do_i_find_yesterday_s_date">How do I find yesterday's date?</a></li>
49 <li><a href="#does_perl_have_a_year_2000_problem_is_perl_y2k_compliant">Does Perl have a Year 2000 problem? Is Perl Y2K compliant?</a></li>
50 </ul>
52 <li><a href="#data__strings">Data: Strings</a></li>
53 <ul>
55 <li><a href="#how_do_i_validate_input">How do I validate input?</a></li>
56 <li><a href="#how_do_i_unescape_a_string">How do I unescape a string?</a></li>
57 <li><a href="#how_do_i_remove_consecutive_pairs_of_characters">How do I remove consecutive pairs of characters?</a></li>
58 <li><a href="#how_do_i_expand_function_calls_in_a_string">How do I expand function calls in a string?</a></li>
59 <li><a href="#how_do_i_find_matching_nesting_anything">How do I find matching/nesting anything?</a></li>
60 <li><a href="#how_do_i_reverse_a_string">How do I reverse a string?</a></li>
61 <li><a href="#how_do_i_expand_tabs_in_a_string">How do I expand tabs in a string?</a></li>
62 <li><a href="#how_do_i_reformat_a_paragraph">How do I reformat a paragraph?</a></li>
63 <li><a href="#how_can_i_access_or_change_n_characters_of_a_string">How can I access or change N characters of a string?</a></li>
64 <li><a href="#how_do_i_change_the_nth_occurrence_of_something">How do I change the Nth occurrence of something?</a></li>
65 <li><a href="#how_can_i_count_the_number_of_occurrences_of_a_substring_within_a_string">How can I count the number of occurrences of a substring within a string?</a></li>
66 <li><a href="#how_do_i_capitalize_all_the_words_on_one_line">How do I capitalize all the words on one line?</a></li>
67 <li><a href="#how_can_i_split_a__character__delimited_string_except_when_inside__character_">How can I split a [character] delimited string except when inside [character]?</a></li>
68 <li><a href="#how_do_i_strip_blank_space_from_the_beginning_end_of_a_string">How do I strip blank space from the beginning/end of a string?</a></li>
69 <li><a href="#how_do_i_pad_a_string_with_blanks_or_pad_a_number_with_zeroes">How do I pad a string with blanks or pad a number with zeroes?</a></li>
70 <li><a href="#how_do_i_extract_selected_columns_from_a_string">How do I extract selected columns from a string?</a></li>
71 <li><a href="#how_do_i_find_the_soundex_value_of_a_string">How do I find the soundex value of a string?</a></li>
72 <li><a href="#how_can_i_expand_variables_in_text_strings">How can I expand variables in text strings?</a></li>
73 <li><a href="#what_s_wrong_with_always_quoting__vars">What's wrong with always quoting ``$vars''?</a></li>
74 <li><a href="#why_don_t_my___here_documents_work">Why don't my &lt;&lt;HERE documents work?</a></li>
75 </ul>
77 <li><a href="#data__arrays">Data: Arrays</a></li>
78 <ul>
80 <li><a href="#what_is_the_difference_between_a_list_and_an_array">What is the difference between a list and an array?</a></li>
81 <li><a href="#what_is_the_difference_between__array_1__and__array_1_">What is the difference between $array[1] and @array[1]?</a></li>
82 <li><a href="#how_can_i_remove_duplicate_elements_from_a_list_or_array">How can I remove duplicate elements from a list or array?</a></li>
83 <li><a href="#how_can_i_tell_whether_a_certain_element_is_contained_in_a_list_or_array">How can I tell whether a certain element is contained in a list or array?</a></li>
84 <li><a href="#how_do_i_compute_the_difference_of_two_arrays_how_do_i_compute_the_intersection_of_two_arrays">How do I compute the difference of two arrays? How do I compute the intersection of two arrays?</a></li>
85 <li><a href="#how_do_i_test_whether_two_arrays_or_hashes_are_equal">How do I test whether two arrays or hashes are equal?</a></li>
86 <li><a href="#how_do_i_find_the_first_array_element_for_which_a_condition_is_true">How do I find the first array element for which a condition is true?</a></li>
87 <li><a href="#how_do_i_handle_linked_lists">How do I handle linked lists?</a></li>
88 <li><a href="#how_do_i_handle_circular_lists">How do I handle circular lists?</a></li>
89 <li><a href="#how_do_i_shuffle_an_array_randomly">How do I shuffle an array randomly?</a></li>
90 <li><a href="#how_do_i_process_modify_each_element_of_an_array">How do I process/modify each element of an array?</a></li>
91 <li><a href="#how_do_i_select_a_random_element_from_an_array">How do I select a random element from an array?</a></li>
92 <li><a href="#how_do_i_permute_n_elements_of_a_list">How do I permute N elements of a list?</a></li>
93 <li><a href="#how_do_i_sort_an_array_by__anything_">How do I sort an array by (anything)?</a></li>
94 <li><a href="#how_do_i_manipulate_arrays_of_bits">How do I manipulate arrays of bits?</a></li>
95 <li><a href="#why_does_defined___return_true_on_empty_arrays_and_hashes">Why does <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_defined"><code>defined()</code></a> return true on empty arrays and hashes?</a></li>
96 </ul>
98 <li><a href="#data__hashes__associative_arrays_">Data: Hashes (Associative Arrays)</a></li>
99 <ul>
101 <li><a href="#how_do_i_process_an_entire_hash">How do I process an entire hash?</a></li>
102 <li><a href="#what_happens_if_i_add_or_remove_keys_from_a_hash_while_iterating_over_it">What happens if I add or remove keys from a hash while iterating over it?</a></li>
103 <li><a href="#how_do_i_look_up_a_hash_element_by_value">How do I look up a hash element by value?</a></li>
104 <li><a href="#how_can_i_know_how_many_entries_are_in_a_hash">How can I know how many entries are in a hash?</a></li>
105 <li><a href="#how_do_i_sort_a_hash__optionally_by_value_instead_of_key_">How do I sort a hash (optionally by value instead of key)?</a></li>
106 <li><a href="#how_can_i_always_keep_my_hash_sorted">How can I always keep my hash sorted?</a></li>
107 <li><a href="#what_s_the_difference_between_delete_and_undef_with_hashes">What's the difference between ``delete'' and ``undef'' with hashes?</a></li>
108 <li><a href="#why_don_t_my_tied_hashes_make_the_defined_exists_distinction">Why don't my tied hashes make the defined/exists distinction?</a></li>
109 <li><a href="#how_do_i_reset_an_each___operation_partway_through">How do I reset an <code>each()</code> operation part-way through?</a></li>
110 <li><a href="#how_can_i_get_the_unique_keys_from_two_hashes">How can I get the unique keys from two hashes?</a></li>
111 <li><a href="#how_can_i_store_a_multidimensional_array_in_a_dbm_file">How can I store a multidimensional array in a DBM file?</a></li>
112 <li><a href="#how_can_i_make_my_hash_remember_the_order_i_put_elements_into_it">How can I make my hash remember the order I put elements into it?</a></li>
113 <li><a href="#why_does_passing_a_subroutine_an_undefined_element_in_a_hash_create_it">Why does passing a subroutine an undefined element in a hash create it?</a></li>
114 <li><a href="#how_can_i_make_the_perl_equivalent_of_a_c_structure_c___class_hash_or_array_of_hashes_or_arrays">How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?</a></li>
115 <li><a href="#how_can_i_use_a_reference_as_a_hash_key">How can I use a reference as a hash key?</a></li>
116 </ul>
118 <li><a href="#data__misc">Data: Misc</a></li>
119 <ul>
121 <li><a href="#how_do_i_handle_binary_data_correctly">How do I handle binary data correctly?</a></li>
122 <li><a href="#how_do_i_determine_whether_a_scalar_is_a_number_whole_integer_float">How do I determine whether a scalar is a number/whole/integer/float?</a></li>
123 <li><a href="#how_do_i_keep_persistent_data_across_program_calls">How do I keep persistent data across program calls?</a></li>
124 <li><a href="#how_do_i_print_out_or_copy_a_recursive_data_structure">How do I print out or copy a recursive data structure?</a></li>
125 <li><a href="#how_do_i_define_methods_for_every_class_object">How do I define methods for every class/object?</a></li>
126 <li><a href="#how_do_i_verify_a_credit_card_checksum">How do I verify a credit card checksum?</a></li>
127 <li><a href="#how_do_i_pack_arrays_of_doubles_or_floats_for_xs_code">How do I pack arrays of doubles or floats for XS code?</a></li>
128 </ul>
130 <li><a href="#author_and_copyright">AUTHOR AND COPYRIGHT</a></li>
131 </ul>
132 <!-- INDEX END -->
134 <hr />
136 </p>
137 <h1><a name="name">NAME</a></h1>
138 <p>perlfaq4 - Data Manipulation ($Revision: 1.73 $, $Date: 2005/12/31 00:54:37 $)</p>
140 </p>
141 <hr />
142 <h1><a name="description">DESCRIPTION</a></h1>
143 <p>This section of the FAQ answers questions related to manipulating
144 numbers, dates, strings, arrays, hashes, and miscellaneous data issues.</p>
146 </p>
147 <hr />
148 <h1><a name="data__numbers">Data: Numbers</a></h1>
150 </p>
151 <h2><a name="why_am_i_getting_long_decimals__eg__19_9499999999999__instead_of_the_numbers_i_should_be_getting__eg__19_95_">Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?</a></h2>
152 <p>Internally, your computer represents floating-point numbers
153 in binary. Digital (as in powers of two) computers cannot
154 store all numbers exactly. Some real numbers lose precision
155 in the process. This is a problem with how computers store
156 numbers and affects all computer languages, not just Perl.</p>
157 <p><a href="file://C|\msysgit\mingw\html/pod/perlnumber.html">the perlnumber manpage</a> show the gory details of number
158 representations and conversions.</p>
159 <p>To limit the number of decimal places in your numbers, you
160 can use the printf or sprintf function. See the
161 <a href="file://C|\msysgit\mingw\html/pod/perlop.html">``Floating Point Arithmetic''</a> for more details.</p>
162 <pre>
163 printf &quot;%.2f&quot;, 10/3;</pre>
164 <pre>
165 my $number = sprintf &quot;%.2f&quot;, 10/3;</pre>
167 </p>
168 <h2><a name="why_is_int___broken">Why is <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_int"><code>int()</code></a> broken?</a></h2>
169 <p>Your <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_int"><code>int()</code></a> is most probably working just fine. It's the numbers that
170 aren't quite what you think.</p>
171 <p>First, see the above item ``Why am I getting long decimals
172 (eg, 19.9499999999999) instead of the numbers I should be getting
173 (eg, 19.95)?''.</p>
174 <p>For example, this</p>
175 <pre>
176 print int(0.6/0.2-2), &quot;\n&quot;;</pre>
177 <p>will in most computers print 0, not 1, because even such simple
178 numbers as 0.6 and 0.2 cannot be presented exactly by floating-point
179 numbers. What you think in the above as 'three' is really more like
180 2.9999999999999995559.</p>
182 </p>
183 <h2><a name="why_isn_t_my_octal_data_interpreted_correctly">Why isn't my octal data interpreted correctly?</a></h2>
184 <p>Perl only understands octal and hex numbers as such when they occur as
185 literals in your program. Octal literals in perl must start with a
186 leading ``0'' and hexadecimal literals must start with a leading ``0x''.
187 If they are read in from somewhere and assigned, no automatic
188 conversion takes place. You must explicitly use <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_oct"><code>oct()</code></a> or <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_hex"><code>hex()</code></a> if you
189 want the values converted to decimal. <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_oct"><code>oct()</code></a> interprets hex (``0x350''),
190 octal (``0350'' or even without the leading ``0'', like ``377'') and binary
191 (``0b1010'') numbers, while <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_hex"><code>hex()</code></a> only converts hexadecimal ones, with
192 or without a leading ``0x'', like ``0x255'', ``3A'', ``ff'', or ``deadbeef''.
193 The inverse mapping from decimal to octal can be done with either the
194 ``%o'' or ``%O'' <code>sprintf()</code> formats.</p>
195 <p>This problem shows up most often when people try using chmod(), mkdir(),
196 umask(), or sysopen(), which by widespread tradition typically take
197 permissions in octal.</p>
198 <pre>
199 chmod(644, $file); # WRONG
200 chmod(0644, $file); # right</pre>
201 <p>Note the mistake in the first line was specifying the decimal literal
202 644, rather than the intended octal literal 0644. The problem can
203 be seen with:</p>
204 <pre>
205 printf(&quot;%#o&quot;,644); # prints 01204</pre>
206 <p>Surely you had not intended <code>chmod(01204, $file);</code> - did you? If you
207 want to use numeric literals as arguments to <code>chmod()</code> et al. then please
208 try to express them as octal constants, that is with a leading zero and
209 with the following digits restricted to the set 0..7.</p>
211 </p>
212 <h2><a name="does_perl_have_a_round___function_what_about_ceil___and_floor___trig_functions">Does Perl have a <code>round()</code> function? What about <code>ceil()</code> and floor()? Trig functions?</a></h2>
213 <p>Remember that <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_int"><code>int()</code></a> merely truncates toward 0. For rounding to a
214 certain number of digits, <code>sprintf()</code> or <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_printf"><code>printf()</code></a> is usually the easiest
215 route.</p>
216 <pre>
217 printf(&quot;%.3f&quot;, 3.1415926535); # prints 3.142</pre>
218 <p>The POSIX module (part of the standard Perl distribution) implements
219 ceil(), floor(), and a number of other mathematical and trigonometric
220 functions.</p>
221 <pre>
222 use POSIX;
223 $ceil = ceil(3.5); # 4
224 $floor = floor(3.5); # 3</pre>
225 <p>In 5.000 to 5.003 perls, trigonometry was done in the Math::Complex
226 module. With 5.004, the Math::Trig module (part of the standard Perl
227 distribution) implements the trigonometric functions. Internally it
228 uses the Math::Complex module and some functions can break out from
229 the real axis into the complex plane, for example the inverse sine of
230 2.</p>
231 <p>Rounding in financial applications can have serious implications, and
232 the rounding method used should be specified precisely. In these
233 cases, it probably pays not to trust whichever system rounding is
234 being used by Perl, but to instead implement the rounding function you
235 need yourself.</p>
236 <p>To see why, notice how you'll still have an issue on half-way-point
237 alternation:</p>
238 <pre>
239 for ($i = 0; $i &lt; 1.01; $i += 0.05) { printf &quot;%.1f &quot;,$i}</pre>
240 <pre>
241 0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7
242 0.8 0.8 0.9 0.9 1.0 1.0</pre>
243 <p>Don't blame Perl. It's the same as in C. IEEE says we have to do this.
244 Perl numbers whose absolute values are integers under 2**31 (on 32 bit
245 machines) will work pretty much like mathematical integers. Other numbers
246 are not guaranteed.</p>
248 </p>
249 <h2><a name="how_do_i_convert_between_numeric_representations_bases_radixes">How do I convert between numeric representations/bases/radixes?</a></h2>
250 <p>As always with Perl there is more than one way to do it. Below
251 are a few examples of approaches to making common conversions
252 between number representations. This is intended to be representational
253 rather than exhaustive.</p>
254 <p>Some of the examples below use the Bit::Vector module from CPAN.
255 The reason you might choose Bit::Vector over the perl built in
256 functions is that it works with numbers of ANY size, that it is
257 optimized for speed on some operations, and for at least some
258 programmers the notation might be familiar.</p>
259 <dl>
260 <dt><strong><a name="item_how_do_i_convert_hexadecimal_into_decimal">How do I convert hexadecimal into decimal</a></strong>
262 <dd>
263 <p>Using perl's built in conversion of 0x notation:</p>
264 </dd>
265 <dd>
266 <pre>
267 $dec = 0xDEADBEEF;</pre>
268 </dd>
269 <dd>
270 <p>Using the hex function:</p>
271 </dd>
272 <dd>
273 <pre>
274 $dec = hex(&quot;DEADBEEF&quot;);</pre>
275 </dd>
276 <dd>
277 <p>Using pack:</p>
278 </dd>
279 <dd>
280 <pre>
281 $dec = unpack(&quot;N&quot;, pack(&quot;H8&quot;, substr(&quot;0&quot; x 8 . &quot;DEADBEEF&quot;, -8)));</pre>
282 </dd>
283 <dd>
284 <p>Using the CPAN module Bit::Vector:</p>
285 </dd>
286 <dd>
287 <pre>
288 use Bit::Vector;
289 $vec = Bit::Vector-&gt;new_Hex(32, &quot;DEADBEEF&quot;);
290 $dec = $vec-&gt;to_Dec();</pre>
291 </dd>
292 </li>
293 <dt><strong><a name="item_how_do_i_convert_from_decimal_to_hexadecimal">How do I convert from decimal to hexadecimal</a></strong>
295 <dd>
296 <p>Using sprintf:</p>
297 </dd>
298 <dd>
299 <pre>
300 $hex = sprintf(&quot;%X&quot;, 3735928559); # upper case A-F
301 $hex = sprintf(&quot;%x&quot;, 3735928559); # lower case a-f</pre>
302 </dd>
303 <dd>
304 <p>Using unpack:</p>
305 </dd>
306 <dd>
307 <pre>
308 $hex = unpack(&quot;H*&quot;, pack(&quot;N&quot;, 3735928559));</pre>
309 </dd>
310 <dd>
311 <p>Using Bit::Vector:</p>
312 </dd>
313 <dd>
314 <pre>
315 use Bit::Vector;
316 $vec = Bit::Vector-&gt;new_Dec(32, -559038737);
317 $hex = $vec-&gt;to_Hex();</pre>
318 </dd>
319 <dd>
320 <p>And Bit::Vector supports odd bit counts:</p>
321 </dd>
322 <dd>
323 <pre>
324 use Bit::Vector;
325 $vec = Bit::Vector-&gt;new_Dec(33, 3735928559);
326 $vec-&gt;Resize(32); # suppress leading 0 if unwanted
327 $hex = $vec-&gt;to_Hex();</pre>
328 </dd>
329 </li>
330 <dt><strong><a name="item_how_do_i_convert_from_octal_to_decimal">How do I convert from octal to decimal</a></strong>
332 <dd>
333 <p>Using Perl's built in conversion of numbers with leading zeros:</p>
334 </dd>
335 <dd>
336 <pre>
337 $dec = 033653337357; # note the leading 0!</pre>
338 </dd>
339 <dd>
340 <p>Using the oct function:</p>
341 </dd>
342 <dd>
343 <pre>
344 $dec = oct(&quot;33653337357&quot;);</pre>
345 </dd>
346 <dd>
347 <p>Using Bit::Vector:</p>
348 </dd>
349 <dd>
350 <pre>
351 use Bit::Vector;
352 $vec = Bit::Vector-&gt;new(32);
353 $vec-&gt;Chunk_List_Store(3, split(//, reverse &quot;33653337357&quot;));
354 $dec = $vec-&gt;to_Dec();</pre>
355 </dd>
356 </li>
357 <dt><strong><a name="item_how_do_i_convert_from_decimal_to_octal">How do I convert from decimal to octal</a></strong>
359 <dd>
360 <p>Using sprintf:</p>
361 </dd>
362 <dd>
363 <pre>
364 $oct = sprintf(&quot;%o&quot;, 3735928559);</pre>
365 </dd>
366 <dd>
367 <p>Using Bit::Vector:</p>
368 </dd>
369 <dd>
370 <pre>
371 use Bit::Vector;
372 $vec = Bit::Vector-&gt;new_Dec(32, -559038737);
373 $oct = reverse join('', $vec-&gt;Chunk_List_Read(3));</pre>
374 </dd>
375 </li>
376 <dt><strong><a name="item_how_do_i_convert_from_binary_to_decimal">How do I convert from binary to decimal</a></strong>
378 <dd>
379 <p>Perl 5.6 lets you write binary numbers directly with
380 the 0b notation:</p>
381 </dd>
382 <dd>
383 <pre>
384 $number = 0b10110110;</pre>
385 </dd>
386 <dd>
387 <p>Using oct:</p>
388 </dd>
389 <dd>
390 <pre>
391 my $input = &quot;10110110&quot;;
392 $decimal = oct( &quot;0b$input&quot; );</pre>
393 </dd>
394 <dd>
395 <p>Using pack and ord:</p>
396 </dd>
397 <dd>
398 <pre>
399 $decimal = ord(pack('B8', '10110110'));</pre>
400 </dd>
401 <dd>
402 <p>Using pack and unpack for larger strings:</p>
403 </dd>
404 <dd>
405 <pre>
406 $int = unpack(&quot;N&quot;, pack(&quot;B32&quot;,
407 substr(&quot;0&quot; x 32 . &quot;11110101011011011111011101111&quot;, -32)));
408 $dec = sprintf(&quot;%d&quot;, $int);</pre>
409 </dd>
410 <dd>
411 <pre>
412 # substr() is used to left pad a 32 character string with zeros.</pre>
413 </dd>
414 <dd>
415 <p>Using Bit::Vector:</p>
416 </dd>
417 <dd>
418 <pre>
419 $vec = Bit::Vector-&gt;new_Bin(32, &quot;11011110101011011011111011101111&quot;);
420 $dec = $vec-&gt;to_Dec();</pre>
421 </dd>
422 </li>
423 <dt><strong><a name="item_how_do_i_convert_from_decimal_to_binary">How do I convert from decimal to binary</a></strong>
425 <dd>
426 <p>Using sprintf (perl 5.6+):</p>
427 </dd>
428 <dd>
429 <pre>
430 $bin = sprintf(&quot;%b&quot;, 3735928559);</pre>
431 </dd>
432 <dd>
433 <p>Using unpack:</p>
434 </dd>
435 <dd>
436 <pre>
437 $bin = unpack(&quot;B*&quot;, pack(&quot;N&quot;, 3735928559));</pre>
438 </dd>
439 <dd>
440 <p>Using Bit::Vector:</p>
441 </dd>
442 <dd>
443 <pre>
444 use Bit::Vector;
445 $vec = Bit::Vector-&gt;new_Dec(32, -559038737);
446 $bin = $vec-&gt;to_Bin();</pre>
447 </dd>
448 <dd>
449 <p>The remaining transformations (e.g. hex -&gt; oct, bin -&gt; hex, etc.)
450 are left as an exercise to the inclined reader.</p>
451 </dd>
452 </li>
453 </dl>
455 </p>
456 <h2><a name="why_doesn_t___work_the_way_i_want_it_to">Why doesn't &amp; work the way I want it to?</a></h2>
457 <p>The behavior of binary arithmetic operators depends on whether they're
458 used on numbers or strings. The operators treat a string as a series
459 of bits and work with that (the string <code>&quot;3&quot;</code> is the bit pattern
460 <code>00110011</code>). The operators work with the binary form of a number
461 (the number <code>3</code> is treated as the bit pattern <code>00000011</code>).</p>
462 <p>So, saying <code>11 &amp; 3</code> performs the ``and'' operation on numbers (yielding
463 <code>3</code>). Saying <code>&quot;11&quot; &amp; &quot;3&quot;</code> performs the ``and'' operation on strings
464 (yielding <code>&quot;1&quot;</code>).</p>
465 <p>Most problems with <code>&amp;</code> and <code>|</code> arise because the programmer thinks
466 they have a number but really it's a string. The rest arise because
467 the programmer says:</p>
468 <pre>
469 if (&quot;\020\020&quot; &amp; &quot;\101\101&quot;) {
470 # ...
471 }</pre>
472 <p>but a string consisting of two null bytes (the result of <code>&quot;\020\020&quot;
473 &amp; &quot;\101\101&quot;</code>) is not a false value in Perl. You need:</p>
474 <pre>
475 if ( (&quot;\020\020&quot; &amp; &quot;\101\101&quot;) !~ /[^\000]/) {
476 # ...
477 }</pre>
479 </p>
480 <h2><a name="how_do_i_multiply_matrices">How do I multiply matrices?</a></h2>
481 <p>Use the Math::Matrix or Math::MatrixReal modules (available from CPAN)
482 or the PDL extension (also available from CPAN).</p>
484 </p>
485 <h2><a name="how_do_i_perform_an_operation_on_a_series_of_integers">How do I perform an operation on a series of integers?</a></h2>
486 <p>To call a function on each element in an array, and collect the
487 results, use:</p>
488 <pre>
489 @results = map { my_func($_) } @array;</pre>
490 <p>For example:</p>
491 <pre>
492 @triple = map { 3 * $_ } @single;</pre>
493 <p>To call a function on each element of an array, but ignore the
494 results:</p>
495 <pre>
496 foreach $iterator (@array) {
497 some_func($iterator);
498 }</pre>
499 <p>To call a function on each integer in a (small) range, you <strong>can</strong> use:</p>
500 <pre>
501 @results = map { some_func($_) } (5 .. 25);</pre>
502 <p>but you should be aware that the <code>..</code> operator creates an array of
503 all integers in the range. This can take a lot of memory for large
504 ranges. Instead use:</p>
505 <pre>
506 @results = ();
507 for ($i=5; $i &lt; 500_005; $i++) {
508 push(@results, some_func($i));
509 }</pre>
510 <p>This situation has been fixed in Perl5.005. Use of <code>..</code> in a <code>for</code>
511 loop will iterate over the range, without creating the entire range.</p>
512 <pre>
513 for my $i (5 .. 500_005) {
514 push(@results, some_func($i));
515 }</pre>
516 <p>will not create a list of 500,000 integers.</p>
518 </p>
519 <h2><a name="how_can_i_output_roman_numerals">How can I output Roman numerals?</a></h2>
520 <p>Get the <a href="http://www.cpan.org/modules/by-module/Roman">http://www.cpan.org/modules/by-module/Roman</a> module.</p>
522 </p>
523 <h2><a name="why_aren_t_my_random_numbers_random">Why aren't my random numbers random?</a></h2>
524 <p>If you're using a version of Perl before 5.004, you must call <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_srand"><code>srand</code></a>
525 once at the start of your program to seed the random number generator.</p>
526 <pre>
527 BEGIN { srand() if $] &lt; 5.004 }</pre>
528 <p>5.004 and later automatically call <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_srand"><code>srand</code></a> at the beginning. Don't
529 call <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_srand"><code>srand</code></a> more than once---you make your numbers less random, rather
530 than more.</p>
531 <p>Computers are good at being predictable and bad at being random
532 (despite appearances caused by bugs in your programs :-). see the
533 <em>random</em> article in the ``Far More Than You Ever Wanted To Know''
534 collection in <a href="http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz">http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz</a> , courtesy of
535 Tom Phoenix, talks more about this. John von Neumann said, ``Anyone
536 who attempts to generate random numbers by deterministic means is, of
537 course, living in a state of sin.''</p>
538 <p>If you want numbers that are more random than <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_rand"><code>rand</code></a> with <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_srand"><code>srand</code></a>
539 provides, you should also check out the Math::TrulyRandom module from
540 CPAN. It uses the imperfections in your system's timer to generate
541 random numbers, but this takes quite a while. If you want a better
542 pseudorandom generator than comes with your operating system, look at
543 ``Numerical Recipes in C'' at <a href="http://www.nr.com/">http://www.nr.com/</a> .</p>
545 </p>
546 <h2><a name="how_do_i_get_a_random_number_between_x_and_y">How do I get a random number between X and Y?</a></h2>
547 <p><a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_rand"><code>rand($x)</code></a> returns a number such that
548 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_rand"><code>0 &lt;= rand($x) &lt; $x</code></a>. Thus what you want to have perl
549 figure out is a random number in the range from 0 to the
550 difference between your <em>X</em> and <em>Y</em>.</p>
551 <p>That is, to get a number between 10 and 15, inclusive, you
552 want a random number between 0 and 5 that you can then add
553 to 10.</p>
554 <pre>
555 my $number = 10 + int rand( 15-10+1 );</pre>
556 <p>Hence you derive the following simple function to abstract
557 that. It selects a random integer between the two given
558 integers (inclusive), For example: <code>random_int_in(50,120)</code>.</p>
559 <pre>
560 sub random_int_in ($$) {
561 my($min, $max) = @_;
562 # Assumes that the two arguments are integers themselves!
563 return $min if $min == $max;
564 ($min, $max) = ($max, $min) if $min &gt; $max;
565 return $min + int rand(1 + $max - $min);
566 }</pre>
568 </p>
569 <hr />
570 <h1><a name="data__dates">Data: Dates</a></h1>
572 </p>
573 <h2><a name="how_do_i_find_the_day_or_week_of_the_year">How do I find the day or week of the year?</a></h2>
574 <p>The localtime function returns the day of the year. Without an
575 argument localtime uses the current time.</p>
576 <pre>
577 $day_of_year = (localtime)[7];</pre>
578 <p>The POSIX module can also format a date as the day of the year or
579 week of the year.</p>
580 <pre>
581 use POSIX qw/strftime/;
582 my $day_of_year = strftime &quot;%j&quot;, localtime;
583 my $week_of_year = strftime &quot;%W&quot;, localtime;</pre>
584 <p>To get the day of year for any date, use the Time::Local module to get
585 a time in epoch seconds for the argument to localtime.</p>
586 <pre>
587 use POSIX qw/strftime/;
588 use Time::Local;
589 my $week_of_year = strftime &quot;%W&quot;,
590 localtime( timelocal( 0, 0, 0, 18, 11, 1987 ) );</pre>
591 <p>The Date::Calc module provides two functions to calculate these.</p>
592 <pre>
593 use Date::Calc;
594 my $day_of_year = Day_of_Year( 1987, 12, 18 );
595 my $week_of_year = Week_of_Year( 1987, 12, 18 );</pre>
597 </p>
598 <h2><a name="how_do_i_find_the_current_century_or_millennium">How do I find the current century or millennium?</a></h2>
599 <p>Use the following simple functions:</p>
600 <pre>
601 sub get_century {
602 return int((((localtime(shift || time))[5] + 1999))/100);
603 }</pre>
604 <pre>
605 sub get_millennium {
606 return 1+int((((localtime(shift || time))[5] + 1899))/1000);
607 }</pre>
608 <p>On some systems, the POSIX module's <code>strftime()</code> function has
609 been extended in a non-standard way to use a <code>%C</code> format,
610 which they sometimes claim is the ``century''. It isn't,
611 because on most such systems, this is only the first two
612 digits of the four-digit year, and thus cannot be used to
613 reliably determine the current century or millennium.</p>
615 </p>
616 <h2><a name="how_can_i_compare_two_dates_and_find_the_difference">How can I compare two dates and find the difference?</a></h2>
617 <p>(contributed by brian d foy)</p>
618 <p>You could just store all your dates as a number and then subtract. Life
619 isn't always that simple though. If you want to work with formatted
620 dates, the Date::Manip, Date::Calc, or DateTime modules can help you.</p>
622 </p>
623 <h2><a name="how_can_i_take_a_string_and_turn_it_into_epoch_seconds">How can I take a string and turn it into epoch seconds?</a></h2>
624 <p>If it's a regular enough string that it always has the same format,
625 you can split it up and pass the parts to <code>timelocal</code> in the standard
626 Time::Local module. Otherwise, you should look into the Date::Calc
627 and Date::Manip modules from CPAN.</p>
629 </p>
630 <h2><a name="how_can_i_find_the_julian_day">How can I find the Julian Day?</a></h2>
631 <p>(contributed by brian d foy and Dave Cross)</p>
632 <p>You can use the Time::JulianDay module available on CPAN. Ensure that
633 you really want to find a Julian day, though, as many people have
634 different ideas about Julian days. See
635 <a href="http://www.hermetic.ch/cal_stud/jdn.htm">http://www.hermetic.ch/cal_stud/jdn.htm</a> for instance.</p>
636 <p>You can also try the DateTime module, which can convert a date/time
637 to a Julian Day.</p>
638 <pre>
639 $ perl -MDateTime -le'print DateTime-&gt;today-&gt;jd'
640 2453401.5</pre>
641 <p>Or the modified Julian Day</p>
642 <pre>
643 $ perl -MDateTime -le'print DateTime-&gt;today-&gt;mjd'
644 53401</pre>
645 <p>Or even the day of the year (which is what some people think of as a
646 Julian day)</p>
647 <pre>
648 $ perl -MDateTime -le'print DateTime-&gt;today-&gt;doy'
649 31</pre>
651 </p>
652 <h2><a name="how_do_i_find_yesterday_s_date">How do I find yesterday's date?</a></h2>
653 <p>(contributed by brian d foy)</p>
654 <p>Use one of the Date modules. The <code>DateTime</code> module makes it simple, and
655 give you the same time of day, only the day before.</p>
656 <pre>
657 use DateTime;</pre>
658 <pre>
659 my $yesterday = DateTime-&gt;now-&gt;subtract( days =&gt; 1 );</pre>
660 <pre>
661 print &quot;Yesterday was $yesterday\n&quot;;</pre>
662 <p>You can also use the <code>Date::Calc</code> module using its Today_and_Now
663 function.</p>
664 <pre>
665 use Date::Calc qw( Today_and_Now Add_Delta_DHMS );</pre>
666 <pre>
667 my @date_time = Add_Delta_DHMS( Today_and_Now(), -1, 0, 0, 0 );</pre>
668 <pre>
669 print &quot;@date\n&quot;;</pre>
670 <p>Most people try to use the time rather than the calendar to figure out
671 dates, but that assumes that days are twenty-four hours each. For
672 most people, there are two days a year when they aren't: the switch to
673 and from summer time throws this off. Let the modules do the work.</p>
675 </p>
676 <h2><a name="does_perl_have_a_year_2000_problem_is_perl_y2k_compliant">Does Perl have a Year 2000 problem? Is Perl Y2K compliant?</a></h2>
677 <p>Short answer: No, Perl does not have a Year 2000 problem. Yes, Perl is
678 Y2K compliant (whatever that means). The programmers you've hired to
679 use it, however, probably are not.</p>
680 <p>Long answer: The question belies a true understanding of the issue.
681 Perl is just as Y2K compliant as your pencil--no more, and no less.
682 Can you use your pencil to write a non-Y2K-compliant memo? Of course
683 you can. Is that the pencil's fault? Of course it isn't.</p>
684 <p>The date and time functions supplied with Perl (gmtime and localtime)
685 supply adequate information to determine the year well beyond 2000
686 (2038 is when trouble strikes for 32-bit machines). The year returned
687 by these functions when used in a list context is the year minus 1900.
688 For years between 1910 and 1999 this <em>happens</em> to be a 2-digit decimal
689 number. To avoid the year 2000 problem simply do not treat the year as
690 a 2-digit number. It isn't.</p>
691 <p>When <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_gmtime"><code>gmtime()</code></a> and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_localtime"><code>localtime()</code></a> are used in scalar context they return
692 a timestamp string that contains a fully-expanded year. For example,
693 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_gmtime"><code>$timestamp = gmtime(1005613200)</code></a> sets $timestamp to ``Tue Nov 13 01:00:00
694 2001''. There's no year 2000 problem here.</p>
695 <p>That doesn't mean that Perl can't be used to create non-Y2K compliant
696 programs. It can. But so can your pencil. It's the fault of the user,
697 not the language. At the risk of inflaming the NRA: ``Perl doesn't
698 break Y2K, people do.'' See <a href="http://www.perl.org/about/y2k.html">http://www.perl.org/about/y2k.html</a> for
699 a longer exposition.</p>
701 </p>
702 <hr />
703 <h1><a name="data__strings">Data: Strings</a></h1>
705 </p>
706 <h2><a name="how_do_i_validate_input">How do I validate input?</a></h2>
707 <p>(contributed by brian d foy)</p>
708 <p>There are many ways to ensure that values are what you expect or
709 want to accept. Besides the specific examples that we cover in the
710 perlfaq, you can also look at the modules with ``Assert'' and ``Validate''
711 in their names, along with other modules such as <code>Regexp::Common</code>.</p>
712 <p>Some modules have validation for particular types of input, such
713 as <code>Business::ISBN</code>, <code>Business::CreditCard</code>, <code>Email::Valid</code>,
714 and <code>Data::Validate::IP</code>.</p>
716 </p>
717 <h2><a name="how_do_i_unescape_a_string">How do I unescape a string?</a></h2>
718 <p>It depends just what you mean by ``escape''. URL escapes are dealt
719 with in <a href="file://C|\msysgit\mingw\html/pod/perlfaq9.html">the perlfaq9 manpage</a>. Shell escapes with the backslash (<code>\</code>)
720 character are removed with</p>
721 <pre>
722 s/\\(.)/$1/g;</pre>
723 <p>This won't expand <code>&quot;\n&quot;</code> or <code>&quot;\t&quot;</code> or any other special escapes.</p>
725 </p>
726 <h2><a name="how_do_i_remove_consecutive_pairs_of_characters">How do I remove consecutive pairs of characters?</a></h2>
727 <p>(contributed by brian d foy)</p>
728 <p>You can use the substitution operator to find pairs of characters (or
729 runs of characters) and replace them with a single instance. In this
730 substitution, we find a character in <code>(.)</code>. The memory parentheses
731 store the matched character in the back-reference <code>\1</code> and we use
732 that to require that the same thing immediately follow it. We replace
733 that part of the string with the character in <code>$1</code>.</p>
734 <pre>
735 s/(.)\1/$1/g;</pre>
736 <p>We can also use the transliteration operator, <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_tr_"><code>tr///</code></a>. In this
737 example, the search list side of our <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_tr_"><code>tr///</code></a> contains nothing, but
738 the <code>c</code> option complements that so it contains everything. The
739 replacement list also contains nothing, so the transliteration is
740 almost a no-op since it won't do any replacements (or more exactly,
741 replace the character with itself). However, the <a href="file://C|\msysgit\mingw\html/pod/perlguts.html#item_s"><code>s</code></a> option squashes
742 duplicated and consecutive characters in the string so a character
743 does not show up next to itself</p>
744 <pre>
745 my $str = 'Haarlem'; # in the Netherlands
746 $str =~ tr///cs; # Now Harlem, like in New York</pre>
748 </p>
749 <h2><a name="how_do_i_expand_function_calls_in_a_string">How do I expand function calls in a string?</a></h2>
750 <p>(contributed by brian d foy)</p>
751 <p>This is documented in <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a>, and although it's not the easiest
752 thing to read, it does work. In each of these examples, we call the
753 function inside the braces used to dereference a reference. If we
754 have a more than one return value, we can construct and dereference an
755 anonymous array. In this case, we call the function in list context.</p>
756 <pre>
757 print &quot;The time values are @{ [localtime] }.\n&quot;;</pre>
758 <p>If we want to call the function in scalar context, we have to do a bit
759 more work. We can really have any code we like inside the braces, so
760 we simply have to end with the scalar reference, although how you do
761 that is up to you, and you can use code inside the braces.</p>
762 <pre>
763 print &quot;The time is ${\(scalar localtime)}.\n&quot;</pre>
764 <pre>
765 print &quot;The time is ${ my $x = localtime; \$x }.\n&quot;;</pre>
766 <p>If your function already returns a reference, you don't need to create
767 the reference yourself.</p>
768 <pre>
769 sub timestamp { my $t = localtime; \$t }</pre>
770 <pre>
771 print &quot;The time is ${ timestamp() }.\n&quot;;</pre>
772 <p>The <code>Interpolation</code> module can also do a lot of magic for you. You can
773 specify a variable name, in this case <a href="file://C|\msysgit\mingw\html/pod/perlguts.html#item_e"><code>E</code></a>, to set up a tied hash that
774 does the interpolation for you. It has several other methods to do this
775 as well.</p>
776 <pre>
777 use Interpolation E =&gt; 'eval';
778 print &quot;The time values are $E{localtime()}.\n&quot;;</pre>
779 <p>In most cases, it is probably easier to simply use string concatenation,
780 which also forces scalar context.</p>
781 <pre>
782 print &quot;The time is &quot; . localtime . &quot;.\n&quot;;</pre>
784 </p>
785 <h2><a name="how_do_i_find_matching_nesting_anything">How do I find matching/nesting anything?</a></h2>
786 <p>This isn't something that can be done in one regular expression, no
787 matter how complicated. To find something between two single
788 characters, a pattern like <a href="file://C|\msysgit\mingw\html/pod/perlguts.html#item_x"><code>/x([^x]*)x/</code></a> will get the intervening
789 bits in $1. For multiple ones, then something more like
790 <code>/alpha(.*?)omega/</code> would be needed. But none of these deals with
791 nested patterns. For balanced expressions using <code>(</code>, <code>{</code>, <code>[</code> or
792 <code>&lt;</code> as delimiters, use the CPAN module Regexp::Common, or see
793 <a href="file://C|\msysgit\mingw\html/pod/perlre.html#___code___">(??{ code }) in the perlre manpage</a>. For other cases, you'll have to write a
794 parser.</p>
795 <p>If you are serious about writing a parser, there are a number of
796 modules or oddities that will make your life a lot easier. There are
797 the CPAN modules Parse::RecDescent, Parse::Yapp, and Text::Balanced;
798 and the byacc program. Starting from perl 5.8 the Text::Balanced is
799 part of the standard distribution.</p>
800 <p>One simple destructive, inside-out approach that you might try is to
801 pull out the smallest nesting parts one at a time:</p>
802 <pre>
803 while (s/BEGIN((?:(?!BEGIN)(?!END).)*)END//gs) {
804 # do something with $1
805 }</pre>
806 <p>A more complicated and sneaky approach is to make Perl's regular
807 expression engine do it for you. This is courtesy Dean Inada, and
808 rather has the nature of an Obfuscated Perl Contest entry, but it
809 really does work:</p>
810 <pre>
811 # $_ contains the string to parse
812 # BEGIN and END are the opening and closing markers for the
813 # nested text.</pre>
814 <pre>
815 @( = ('(','');
816 @) = (')','');
817 ($re=$_)=~s/((BEGIN)|(END)|.)/$)[!$3]\Q$1\E$([!$2]/gs;
818 @$ = (eval{/$re/},$@!~/unmatched/i);
819 print join(&quot;\n&quot;,@$[0..$#$]) if( $$[-1] );</pre>
821 </p>
822 <h2><a name="how_do_i_reverse_a_string">How do I reverse a string?</a></h2>
823 <p>Use <code>reverse()</code> in scalar context, as documented in
824 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#reverse">reverse in the perlfunc manpage</a>.</p>
825 <pre>
826 $reversed = reverse $string;</pre>
828 </p>
829 <h2><a name="how_do_i_expand_tabs_in_a_string">How do I expand tabs in a string?</a></h2>
830 <p>You can do it yourself:</p>
831 <pre>
832 1 while $string =~ s/\t+/' ' x (length($&amp;) * 8 - length($`) % 8)/e;</pre>
833 <p>Or you can just use the Text::Tabs module (part of the standard Perl
834 distribution).</p>
835 <pre>
836 use Text::Tabs;
837 @expanded_lines = expand(@lines_with_tabs);</pre>
839 </p>
840 <h2><a name="how_do_i_reformat_a_paragraph">How do I reformat a paragraph?</a></h2>
841 <p>Use Text::Wrap (part of the standard Perl distribution):</p>
842 <pre>
843 use Text::Wrap;
844 print wrap(&quot;\t&quot;, ' ', @paragraphs);</pre>
845 <p>The paragraphs you give to Text::Wrap should not contain embedded
846 newlines. Text::Wrap doesn't justify the lines (flush-right).</p>
847 <p>Or use the CPAN module Text::Autoformat. Formatting files can be easily
848 done by making a shell alias, like so:</p>
849 <pre>
850 alias fmt=&quot;perl -i -MText::Autoformat -n0777 \
851 -e 'print autoformat $_, {all=&gt;1}' $*&quot;</pre>
852 <p>See the documentation for Text::Autoformat to appreciate its many
853 capabilities.</p>
855 </p>
856 <h2><a name="how_can_i_access_or_change_n_characters_of_a_string">How can I access or change N characters of a string?</a></h2>
857 <p>You can access the first characters of a string with substr().
858 To get the first character, for example, start at position 0
859 and grab the string of length 1.</p>
860 <pre>
861 $string = &quot;Just another Perl Hacker&quot;;
862 $first_char = substr( $string, 0, 1 ); # 'J'</pre>
863 <p>To change part of a string, you can use the optional fourth
864 argument which is the replacement string.</p>
865 <pre>
866 substr( $string, 13, 4, &quot;Perl 5.8.0&quot; );</pre>
867 <p>You can also use <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item_substr"><code>substr()</code></a> as an lvalue.</p>
868 <pre>
869 substr( $string, 13, 4 ) = &quot;Perl 5.8.0&quot;;</pre>
871 </p>
872 <h2><a name="how_do_i_change_the_nth_occurrence_of_something">How do I change the Nth occurrence of something?</a></h2>
873 <p>You have to keep track of N yourself. For example, let's say you want
874 to change the fifth occurrence of <code>&quot;whoever&quot;</code> or <code>&quot;whomever&quot;</code> into
875 <code>&quot;whosoever&quot;</code> or <code>&quot;whomsoever&quot;</code>, case insensitively. These
876 all assume that $_ contains the string to be altered.</p>
877 <pre>
878 $count = 0;
879 s{((whom?)ever)}{
880 ++$count == 5 # is it the 5th?
881 ? &quot;${2}soever&quot; # yes, swap
882 : $1 # renege and leave it there
883 }ige;</pre>
884 <p>In the more general case, you can use the <code>/g</code> modifier in a <code>while</code>
885 loop, keeping count of matches.</p>
886 <pre>
887 $WANT = 3;
888 $count = 0;
889 $_ = &quot;One fish two fish red fish blue fish&quot;;
890 while (/(\w+)\s+fish\b/gi) {
891 if (++$count == $WANT) {
892 print &quot;The third fish is a $1 one.\n&quot;;
894 }</pre>
895 <p>That prints out: <code>&quot;The third fish is a red one.&quot;</code> You can also use a
896 repetition count and repeated pattern like this:</p>
897 <pre>
898 /(?:\w+\s+fish\s+){2}(\w+)\s+fish/i;</pre>
900 </p>
901 <h2><a name="how_can_i_count_the_number_of_occurrences_of_a_substring_within_a_string">How can I count the number of occurrences of a substring within a string?</a></h2>
902 <p>There are a number of ways, with varying efficiency. If you want a
903 count of a certain single character (X) within a string, you can use the
904 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_tr_"><code>tr///</code></a> function like so:</p>
905 <pre>
906 $string = &quot;ThisXlineXhasXsomeXx'sXinXit&quot;;
907 $count = ($string =~ tr/X//);
908 print &quot;There are $count X characters in the string&quot;;</pre>
909 <p>This is fine if you are just looking for a single character. However,
910 if you are trying to count multiple character substrings within a
911 larger string, <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_tr_"><code>tr///</code></a> won't work. What you can do is wrap a <code>while()</code>
912 loop around a global pattern match. For example, let's count negative
913 integers:</p>
914 <pre>
915 $string = &quot;-9 55 48 -2 23 -76 4 14 -44&quot;;
916 while ($string =~ /-\d+/g) { $count++ }
917 print &quot;There are $count negative numbers in the string&quot;;</pre>
918 <p>Another version uses a global match in list context, then assigns the
919 result to a scalar, producing a count of the number of matches.</p>
920 <pre>
921 $count = () = $string =~ /-\d+/g;</pre>
923 </p>
924 <h2><a name="how_do_i_capitalize_all_the_words_on_one_line">How do I capitalize all the words on one line?</a></h2>
925 <p>To make the first letter of each word upper case:</p>
926 <pre>
927 $line =~ s/\b(\w)/\U$1/g;</pre>
928 <p>This has the strange effect of turning ``<code>don't do it</code>'' into ``<code>Don'T
929 Do It</code>''. Sometimes you might want this. Other times you might need a
930 more thorough solution (Suggested by brian d foy):</p>
931 <pre>
932 $string =~ s/ (
933 (^\w) #at the beginning of the line
934 | # or
935 (\s\w) #preceded by whitespace
937 /\U$1/xg;
938 $string =~ /([\w']+)/\u\L$1/g;</pre>
939 <p>To make the whole line upper case:</p>
940 <pre>
941 $line = uc($line);</pre>
942 <p>To force each word to be lower case, with the first letter upper case:</p>
943 <pre>
944 $line =~ s/(\w+)/\u\L$1/g;</pre>
945 <p>You can (and probably should) enable locale awareness of those
946 characters by placing a <code>use locale</code> pragma in your program.
947 See <a href="file://C|\msysgit\mingw\html/pod/perllocale.html">the perllocale manpage</a> for endless details on locales.</p>
948 <p>This is sometimes referred to as putting something into ``title
949 case'', but that's not quite accurate. Consider the proper
950 capitalization of the movie <em>Dr. Strangelove or: How I Learned to
951 Stop Worrying and Love the Bomb</em>, for example.</p>
952 <p>Damian Conway's <a href="file://C|\msysgit\mingw\html/Text/Autoformat.html">the Text::Autoformat manpage</a> module provides some smart
953 case transformations:</p>
954 <pre>
955 use Text::Autoformat;
956 my $x = &quot;Dr. Strangelove or: How I Learned to Stop &quot;.
957 &quot;Worrying and Love the Bomb&quot;;</pre>
958 <pre>
959 print $x, &quot;\n&quot;;
960 for my $style (qw( sentence title highlight ))
962 print autoformat($x, { case =&gt; $style }), &quot;\n&quot;;
963 }</pre>
965 </p>
966 <h2><a name="how_can_i_split_a__character__delimited_string_except_when_inside__character_">How can I split a [character] delimited string except when inside [character]?</a></h2>
967 <p>Several modules can handle this sort of pasing---Text::Balanced,
968 Text::CSV, Text::CSV_XS, and Text::ParseWords, among others.</p>
969 <p>Take the example case of trying to split a string that is
970 comma-separated into its different fields. You can't use <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_split"><code>split(/,/)</code></a>
971 because you shouldn't split if the comma is inside quotes. For
972 example, take a data line like this:</p>
973 <pre>
974 SAR001,&quot;&quot;,&quot;Cimetrix, Inc&quot;,&quot;Bob Smith&quot;,&quot;CAM&quot;,N,8,1,0,7,&quot;Error, Core Dumped&quot;</pre>
975 <p>Due to the restriction of the quotes, this is a fairly complex
976 problem. Thankfully, we have Jeffrey Friedl, author of
977 <em>Mastering Regular Expressions</em>, to handle these for us. He
978 suggests (assuming your string is contained in $text):</p>
979 <pre>
980 @new = ();
981 push(@new, $+) while $text =~ m{
982 &quot;([^\&quot;\\]*(?:\\.[^\&quot;\\]*)*)&quot;,? # groups the phrase inside the quotes
983 | ([^,]+),?
985 }gx;
986 push(@new, undef) if substr($text,-1,1) eq ',';</pre>
987 <p>If you want to represent quotation marks inside a
988 quotation-mark-delimited field, escape them with backslashes (eg,
989 <code>&quot;like \&quot;this\&quot;&quot;</code>.</p>
990 <p>Alternatively, the Text::ParseWords module (part of the standard Perl
991 distribution) lets you say:</p>
992 <pre>
993 use Text::ParseWords;
994 @new = quotewords(&quot;,&quot;, 0, $text);</pre>
995 <p>There's also a Text::CSV (Comma-Separated Values) module on CPAN.</p>
997 </p>
998 <h2><a name="how_do_i_strip_blank_space_from_the_beginning_end_of_a_string">How do I strip blank space from the beginning/end of a string?</a></h2>
999 <p>(contributed by brian d foy)</p>
1000 <p>A substitution can do this for you. For a single line, you want to
1001 replace all the leading or trailing whitespace with nothing. You
1002 can do that with a pair of substitutions.</p>
1003 <pre>
1004 s/^\s+//;
1005 s/\s+$//;</pre>
1006 <p>You can also write that as a single substitution, although it turns
1007 out the combined statement is slower than the separate ones. That
1008 might not matter to you, though.</p>
1009 <pre>
1010 s/^\s+|\s+$//g;</pre>
1011 <p>In this regular expression, the alternation matches either at the
1012 beginning or the end of the string since the anchors have a lower
1013 precedence than the alternation. With the <code>/g</code> flag, the substitution
1014 makes all possible matches, so it gets both. Remember, the trailing
1015 newline matches the <code>\s+</code>, and the <code>$</code> anchor can match to the
1016 physical end of the string, so the newline disappears too. Just add
1017 the newline to the output, which has the added benefit of preserving
1018 ``blank'' (consisting entirely of whitespace) lines which the <code>^\s+</code>
1019 would remove all by itself.</p>
1020 <pre>
1021 while( &lt;&gt; )
1023 s/^\s+|\s+$//g;
1024 print &quot;$_\n&quot;;
1025 }</pre>
1026 <p>For a multi-line string, you can apply the regular expression
1027 to each logical line in the string by adding the <code>/m</code> flag (for
1028 ``multi-line''). With the <code>/m</code> flag, the <code>$</code> matches <em>before</em> an
1029 embedded newline, so it doesn't remove it. It still removes the
1030 newline at the end of the string.</p>
1031 <pre>
1032 $string =~ s/^\s+|\s+$//gm;</pre>
1033 <p>Remember that lines consisting entirely of whitespace will disappear,
1034 since the first part of the alternation can match the entire string
1035 and replace it with nothing. If need to keep embedded blank lines,
1036 you have to do a little more work. Instead of matching any whitespace
1037 (since that includes a newline), just match the other whitespace.</p>
1038 <pre>
1039 $string =~ s/^[\t\f ]+|[\t\f ]+$//mg;</pre>
1041 </p>
1042 <h2><a name="how_do_i_pad_a_string_with_blanks_or_pad_a_number_with_zeroes">How do I pad a string with blanks or pad a number with zeroes?</a></h2>
1043 <p>In the following examples, <code>$pad_len</code> is the length to which you wish
1044 to pad the string, <code>$text</code> or <code>$num</code> contains the string to be padded,
1045 and <code>$pad_char</code> contains the padding character. You can use a single
1046 character string constant instead of the <code>$pad_char</code> variable if you
1047 know what it is in advance. And in the same way you can use an integer in
1048 place of <code>$pad_len</code> if you know the pad length in advance.</p>
1049 <p>The simplest method uses the <code>sprintf</code> function. It can pad on the left
1050 or right with blanks and on the left with zeroes and it will not
1051 truncate the result. The <code>pack</code> function can only pad strings on the
1052 right with blanks and it will truncate the result to a maximum length of
1053 <code>$pad_len</code>.</p>
1054 <pre>
1055 # Left padding a string with blanks (no truncation):
1056 $padded = sprintf(&quot;%${pad_len}s&quot;, $text);
1057 $padded = sprintf(&quot;%*s&quot;, $pad_len, $text); # same thing</pre>
1058 <pre>
1059 # Right padding a string with blanks (no truncation):
1060 $padded = sprintf(&quot;%-${pad_len}s&quot;, $text);
1061 $padded = sprintf(&quot;%-*s&quot;, $pad_len, $text); # same thing</pre>
1062 <pre>
1063 # Left padding a number with 0 (no truncation):
1064 $padded = sprintf(&quot;%0${pad_len}d&quot;, $num);
1065 $padded = sprintf(&quot;%0*d&quot;, $pad_len, $num); # same thing</pre>
1066 <pre>
1067 # Right padding a string with blanks using pack (will truncate):
1068 $padded = pack(&quot;A$pad_len&quot;,$text);</pre>
1069 <p>If you need to pad with a character other than blank or zero you can use
1070 one of the following methods. They all generate a pad string with the
1071 <a href="file://C|\msysgit\mingw\html/pod/perlguts.html#item_x"><code>x</code></a> operator and combine that with <code>$text</code>. These methods do
1072 not truncate <code>$text</code>.</p>
1073 <p>Left and right padding with any character, creating a new string:</p>
1074 <pre>
1075 $padded = $pad_char x ( $pad_len - length( $text ) ) . $text;
1076 $padded = $text . $pad_char x ( $pad_len - length( $text ) );</pre>
1077 <p>Left and right padding with any character, modifying <code>$text</code> directly:</p>
1078 <pre>
1079 substr( $text, 0, 0 ) = $pad_char x ( $pad_len - length( $text ) );
1080 $text .= $pad_char x ( $pad_len - length( $text ) );</pre>
1082 </p>
1083 <h2><a name="how_do_i_extract_selected_columns_from_a_string">How do I extract selected columns from a string?</a></h2>
1084 <p>Use <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item_substr"><code>substr()</code></a> or unpack(), both documented in <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html">the perlfunc manpage</a>.
1085 If you prefer thinking in terms of columns instead of widths,
1086 you can use this kind of thing:</p>
1087 <pre>
1088 # determine the unpack format needed to split Linux ps output
1089 # arguments are cut columns
1090 my $fmt = cut2fmt(8, 14, 20, 26, 30, 34, 41, 47, 59, 63, 67, 72);</pre>
1091 <pre>
1092 sub cut2fmt {
1093 my(@positions) = @_;
1094 my $template = '';
1095 my $lastpos = 1;
1096 for my $place (@positions) {
1097 $template .= &quot;A&quot; . ($place - $lastpos) . &quot; &quot;;
1098 $lastpos = $place;
1100 $template .= &quot;A*&quot;;
1101 return $template;
1102 }</pre>
1104 </p>
1105 <h2><a name="how_do_i_find_the_soundex_value_of_a_string">How do I find the soundex value of a string?</a></h2>
1106 <p>(contributed by brian d foy)</p>
1107 <p>You can use the Text::Soundex module. If you want to do fuzzy or close
1108 matching, you might also try the String::Approx, and Text::Metaphone,
1109 and Text::DoubleMetaphone modules.</p>
1111 </p>
1112 <h2><a name="how_can_i_expand_variables_in_text_strings">How can I expand variables in text strings?</a></h2>
1113 <p>Let's assume that you have a string that contains placeholder
1114 variables.</p>
1115 <pre>
1116 $text = 'this has a $foo in it and a $bar';</pre>
1117 <p>You can use a substitution with a double evaluation. The
1118 first /e turns <code>$1</code> into <code>$foo</code>, and the second /e turns
1119 <code>$foo</code> into its value. You may want to wrap this in an
1120 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_eval"><code>eval</code></a>: if you try to get the value of an undeclared variable
1121 while running under <code>use strict</code>, you get a fatal error.</p>
1122 <pre>
1123 eval { $text =~ s/(\$\w+)/$1/eeg };
1124 die if $@;</pre>
1125 <p>It's probably better in the general case to treat those
1126 variables as entries in some special hash. For example:</p>
1127 <pre>
1128 %user_defs = (
1129 foo =&gt; 23,
1130 bar =&gt; 19,
1132 $text =~ s/\$(\w+)/$user_defs{$1}/g;</pre>
1134 </p>
1135 <h2><a name="what_s_wrong_with_always_quoting__vars">What's wrong with always quoting ``$vars''?</a></h2>
1136 <p>The problem is that those double-quotes force stringification--
1137 coercing numbers and references into strings--even when you
1138 don't want them to be strings. Think of it this way: double-quote
1139 expansion is used to produce new strings. If you already
1140 have a string, why do you need more?</p>
1141 <p>If you get used to writing odd things like these:</p>
1142 <pre>
1143 print &quot;$var&quot;; # BAD
1144 $new = &quot;$old&quot;; # BAD
1145 somefunc(&quot;$var&quot;); # BAD</pre>
1146 <p>You'll be in trouble. Those should (in 99.8% of the cases) be
1147 the simpler and more direct:</p>
1148 <pre>
1149 print $var;
1150 $new = $old;
1151 somefunc($var);</pre>
1152 <p>Otherwise, besides slowing you down, you're going to break code when
1153 the thing in the scalar is actually neither a string nor a number, but
1154 a reference:</p>
1155 <pre>
1156 func(\@array);
1157 sub func {
1158 my $aref = shift;
1159 my $oref = &quot;$aref&quot;; # WRONG
1160 }</pre>
1161 <p>You can also get into subtle problems on those few operations in Perl
1162 that actually do care about the difference between a string and a
1163 number, such as the magical <code>++</code> autoincrement operator or the
1164 <code>syscall()</code> function.</p>
1165 <p>Stringification also destroys arrays.</p>
1166 <pre>
1167 @lines = `command`;
1168 print &quot;@lines&quot;; # WRONG - extra blanks
1169 print @lines; # right</pre>
1171 </p>
1172 <h2><a name="why_don_t_my___here_documents_work">Why don't my &lt;&lt;HERE documents work?</a></h2>
1173 <p>Check for these three things:</p>
1174 <dl>
1175 <dt><strong><a name="item_there_must_be_no_space_after_the__3c_3c_part_2e">There must be no space after the &lt;&lt; part.</a></strong>
1177 <dt><strong><a name="item_there">There (probably) should be a semicolon at the end.</a></strong>
1179 <dt><strong><a name="item_t">You can't (easily) have any space in front of the tag.</a></strong>
1181 </dl>
1182 <p>If you want to indent the text in the here document, you
1183 can do this:</p>
1184 <pre>
1185 # all in one
1186 ($VAR = &lt;&lt;HERE_TARGET) =~ s/^\s+//gm;
1187 your text
1188 goes here
1189 HERE_TARGET</pre>
1190 <p>But the HERE_TARGET must still be flush against the margin.
1191 If you want that indented also, you'll have to quote
1192 in the indentation.</p>
1193 <pre>
1194 ($quote = &lt;&lt;' FINIS') =~ s/^\s+//gm;
1195 ...we will have peace, when you and all your works have
1196 perished--and the works of your dark master to whom you
1197 would deliver us. You are a liar, Saruman, and a corrupter
1198 of men's hearts. --Theoden in /usr/src/perl/taint.c
1199 FINIS
1200 $quote =~ s/\s+--/\n--/;</pre>
1201 <p>A nice general-purpose fixer-upper function for indented here documents
1202 follows. It expects to be called with a here document as its argument.
1203 It looks to see whether each line begins with a common substring, and
1204 if so, strips that substring off. Otherwise, it takes the amount of leading
1205 whitespace found on the first line and removes that much off each
1206 subsequent line.</p>
1207 <pre>
1208 sub fix {
1209 local $_ = shift;
1210 my ($white, $leader); # common whitespace and common leading string
1211 if (/^\s*(?:([^\w\s]+)(\s*).*\n)(?:\s*\1\2?.*\n)+$/) {
1212 ($white, $leader) = ($2, quotemeta($1));
1213 } else {
1214 ($white, $leader) = (/^(\s+)/, '');
1216 s/^\s*?$leader(?:$white)?//gm;
1217 return $_;
1218 }</pre>
1219 <p>This works with leading special strings, dynamically determined:</p>
1220 <pre>
1221 $remember_the_main = fix&lt;&lt;' MAIN_INTERPRETER_LOOP';
1222 @@@ int
1223 @@@ runops() {
1224 @@@ SAVEI32(runlevel);
1225 @@@ runlevel++;
1226 @@@ while ( op = (*op-&gt;op_ppaddr)() );
1227 @@@ TAINT_NOT;
1228 @@@ return 0;
1229 @@@ }
1230 MAIN_INTERPRETER_LOOP</pre>
1231 <p>Or with a fixed amount of leading whitespace, with remaining
1232 indentation correctly preserved:</p>
1233 <pre>
1234 $poem = fix&lt;&lt;EVER_ON_AND_ON;
1235 Now far ahead the Road has gone,
1236 And I must follow, if I can,
1237 Pursuing it with eager feet,
1238 Until it joins some larger way
1239 Where many paths and errands meet.
1240 And whither then? I cannot say.
1241 --Bilbo in /usr/src/perl/pp_ctl.c
1242 EVER_ON_AND_ON</pre>
1244 </p>
1245 <hr />
1246 <h1><a name="data__arrays">Data: Arrays</a></h1>
1248 </p>
1249 <h2><a name="what_is_the_difference_between_a_list_and_an_array">What is the difference between a list and an array?</a></h2>
1250 <p>An array has a changeable length. A list does not. An array is something
1251 you can push or pop, while a list is a set of values. Some people make
1252 the distinction that a list is a value while an array is a variable.
1253 Subroutines are passed and return lists, you put things into list
1254 context, you initialize arrays with lists, and you <code>foreach()</code> across
1255 a list. <code>@</code> variables are arrays, anonymous arrays are arrays, arrays
1256 in scalar context behave like the number of elements in them, subroutines
1257 access their arguments through the array <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>@_</code></a>, and push/pop/shift only work
1258 on arrays.</p>
1259 <p>As a side note, there's no such thing as a list in scalar context.
1260 When you say</p>
1261 <pre>
1262 $scalar = (2, 5, 7, 9);</pre>
1263 <p>you're using the comma operator in scalar context, so it uses the scalar
1264 comma operator. There never was a list there at all! This causes the
1265 last value to be returned: 9.</p>
1267 </p>
1268 <h2><a name="what_is_the_difference_between__array_1__and__array_1_">What is the difference between $array[1] and @array[1]?</a></h2>
1269 <p>The former is a scalar value; the latter an array slice, making
1270 it a list with one (scalar) value. You should use $ when you want a
1271 scalar value (most of the time) and @ when you want a list with one
1272 scalar value in it (very, very rarely; nearly never, in fact).</p>
1273 <p>Sometimes it doesn't make a difference, but sometimes it does.
1274 For example, compare:</p>
1275 <pre>
1276 $good[0] = `some program that outputs several lines`;</pre>
1277 <p>with</p>
1278 <pre>
1279 @bad[0] = `same program that outputs several lines`;</pre>
1280 <p>The <code>use warnings</code> pragma and the <strong>-w</strong> flag will warn you about these
1281 matters.</p>
1283 </p>
1284 <h2><a name="how_can_i_remove_duplicate_elements_from_a_list_or_array">How can I remove duplicate elements from a list or array?</a></h2>
1285 <p>(contributed by brian d foy)</p>
1286 <p>Use a hash. When you think the words ``unique'' or ``duplicated'', think
1287 ``hash keys''.</p>
1288 <p>If you don't care about the order of the elements, you could just
1289 create the hash then extract the keys. It's not important how you
1290 create that hash: just that you use <code>keys</code> to get the unique
1291 elements.</p>
1292 <pre>
1293 my %hash = map { $_, 1 } @array;
1294 # or a hash slice: @hash{ @array } = ();
1295 # or a foreach: $hash{$_} = 1 foreach ( @array );</pre>
1296 <pre>
1297 my @unique = keys %hash;</pre>
1298 <p>You can also go through each element and skip the ones you've seen
1299 before. Use a hash to keep track. The first time the loop sees an
1300 element, that element has no key in <code>%Seen</code>. The <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_next"><code>next</code></a> statement
1301 creates the key and immediately uses its value, which is <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_undef"><code>undef</code></a>, so
1302 the loop continues to the <code>push</code> and increments the value for that
1303 key. The next time the loop sees that same element, its key exists in
1304 the hash <em>and</em> the value for that key is true (since it's not 0 or
1305 undef), so the next skips that iteration and the loop goes to the next
1306 element.</p>
1307 <pre>
1308 my @unique = ();
1309 my %seen = ();</pre>
1310 <pre>
1311 foreach my $elem ( @array )
1313 next if $seen{ $elem }++;
1314 push @unique, $elem;
1315 }</pre>
1316 <p>You can write this more briefly using a grep, which does the
1317 same thing.</p>
1318 <pre>
1319 my %seen = ();
1320 my @unique = grep { ! $seen{ $_ }++ } @array;</pre>
1322 </p>
1323 <h2><a name="how_can_i_tell_whether_a_certain_element_is_contained_in_a_list_or_array">How can I tell whether a certain element is contained in a list or array?</a></h2>
1324 <p>(portions of this answer contributed by Anno Siegel)</p>
1325 <p>Hearing the word ``in'' is an <em>in</em>dication that you probably should have
1326 used a hash, not a list or array, to store your data. Hashes are
1327 designed to answer this question quickly and efficiently. Arrays aren't.</p>
1328 <p>That being said, there are several ways to approach this. If you
1329 are going to make this query many times over arbitrary string values,
1330 the fastest way is probably to invert the original array and maintain a
1331 hash whose keys are the first array's values.</p>
1332 <pre>
1333 @blues = qw/azure cerulean teal turquoise lapis-lazuli/;
1334 %is_blue = ();
1335 for (@blues) { $is_blue{$_} = 1 }</pre>
1336 <p>Now you can check whether $is_blue{$some_color}. It might have been a
1337 good idea to keep the blues all in a hash in the first place.</p>
1338 <p>If the values are all small integers, you could use a simple indexed
1339 array. This kind of an array will take up less space:</p>
1340 <pre>
1341 @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
1342 @is_tiny_prime = ();
1343 for (@primes) { $is_tiny_prime[$_] = 1 }
1344 # or simply @istiny_prime[@primes] = (1) x @primes;</pre>
1345 <p>Now you check whether $is_tiny_prime[$some_number].</p>
1346 <p>If the values in question are integers instead of strings, you can save
1347 quite a lot of space by using bit strings instead:</p>
1348 <pre>
1349 @articles = ( 1..10, 150..2000, 2017 );
1350 undef $read;
1351 for (@articles) { vec($read,$_,1) = 1 }</pre>
1352 <p>Now check whether <code>vec($read,$n,1)</code> is true for some <code>$n</code>.</p>
1353 <p>These methods guarantee fast individual tests but require a re-organization
1354 of the original list or array. They only pay off if you have to test
1355 multiple values against the same array.</p>
1356 <p>If you are testing only once, the standard module List::Util exports
1357 the function <code>first</code> for this purpose. It works by stopping once it
1358 finds the element. It's written in C for speed, and its Perl equivalant
1359 looks like this subroutine:</p>
1360 <pre>
1361 sub first (&amp;@) {
1362 my $code = shift;
1363 foreach (@_) {
1364 return $_ if &amp;{$code}();
1366 undef;
1367 }</pre>
1368 <p>If speed is of little concern, the common idiom uses grep in scalar context
1369 (which returns the number of items that passed its condition) to traverse the
1370 entire list. This does have the benefit of telling you how many matches it
1371 found, though.</p>
1372 <pre>
1373 my $is_there = grep $_ eq $whatever, @array;</pre>
1374 <p>If you want to actually extract the matching elements, simply use grep in
1375 list context.</p>
1376 <pre>
1377 my @matches = grep $_ eq $whatever, @array;</pre>
1379 </p>
1380 <h2><a name="how_do_i_compute_the_difference_of_two_arrays_how_do_i_compute_the_intersection_of_two_arrays">How do I compute the difference of two arrays? How do I compute the intersection of two arrays?</a></h2>
1381 <p>Use a hash. Here's code to do both and more. It assumes that
1382 each element is unique in a given array:</p>
1383 <pre>
1384 @union = @intersection = @difference = ();
1385 %count = ();
1386 foreach $element (@array1, @array2) { $count{$element}++ }
1387 foreach $element (keys %count) {
1388 push @union, $element;
1389 push @{ $count{$element} &gt; 1 ? \@intersection : \@difference }, $element;
1390 }</pre>
1391 <p>Note that this is the <em>symmetric difference</em>, that is, all elements in
1392 either A or in B but not in both. Think of it as an xor operation.</p>
1394 </p>
1395 <h2><a name="how_do_i_test_whether_two_arrays_or_hashes_are_equal">How do I test whether two arrays or hashes are equal?</a></h2>
1396 <p>The following code works for single-level arrays. It uses a stringwise
1397 comparison, and does not distinguish defined versus undefined empty
1398 strings. Modify if you have other needs.</p>
1399 <pre>
1400 $are_equal = compare_arrays(\@frogs, \@toads);</pre>
1401 <pre>
1402 sub compare_arrays {
1403 my ($first, $second) = @_;
1404 no warnings; # silence spurious -w undef complaints
1405 return 0 unless @$first == @$second;
1406 for (my $i = 0; $i &lt; @$first; $i++) {
1407 return 0 if $first-&gt;[$i] ne $second-&gt;[$i];
1409 return 1;
1410 }</pre>
1411 <p>For multilevel structures, you may wish to use an approach more
1412 like this one. It uses the CPAN module FreezeThaw:</p>
1413 <pre>
1414 use FreezeThaw qw(cmpStr);
1415 @a = @b = ( &quot;this&quot;, &quot;that&quot;, [ &quot;more&quot;, &quot;stuff&quot; ] );</pre>
1416 <pre>
1417 printf &quot;a and b contain %s arrays\n&quot;,
1418 cmpStr(\@a, \@b) == 0
1419 ? &quot;the same&quot;
1420 : &quot;different&quot;;</pre>
1421 <p>This approach also works for comparing hashes. Here
1422 we'll demonstrate two different answers:</p>
1423 <pre>
1424 use FreezeThaw qw(cmpStr cmpStrHard);</pre>
1425 <pre>
1426 %a = %b = ( &quot;this&quot; =&gt; &quot;that&quot;, &quot;extra&quot; =&gt; [ &quot;more&quot;, &quot;stuff&quot; ] );
1427 $a{EXTRA} = \%b;
1428 $b{EXTRA} = \%a;</pre>
1429 <pre>
1430 printf &quot;a and b contain %s hashes\n&quot;,
1431 cmpStr(\%a, \%b) == 0 ? &quot;the same&quot; : &quot;different&quot;;</pre>
1432 <pre>
1433 printf &quot;a and b contain %s hashes\n&quot;,
1434 cmpStrHard(\%a, \%b) == 0 ? &quot;the same&quot; : &quot;different&quot;;</pre>
1435 <p>The first reports that both those the hashes contain the same data,
1436 while the second reports that they do not. Which you prefer is left as
1437 an exercise to the reader.</p>
1439 </p>
1440 <h2><a name="how_do_i_find_the_first_array_element_for_which_a_condition_is_true">How do I find the first array element for which a condition is true?</a></h2>
1441 <p>To find the first array element which satisfies a condition, you can
1442 use the <code>first()</code> function in the List::Util module, which comes with
1443 Perl 5.8. This example finds the first element that contains ``Perl''.</p>
1444 <pre>
1445 use List::Util qw(first);</pre>
1446 <pre>
1447 my $element = first { /Perl/ } @array;</pre>
1448 <p>If you cannot use List::Util, you can make your own loop to do the
1449 same thing. Once you find the element, you stop the loop with last.</p>
1450 <pre>
1451 my $found;
1452 foreach ( @array )
1454 if( /Perl/ ) { $found = $_; last }
1455 }</pre>
1456 <p>If you want the array index, you can iterate through the indices
1457 and check the array element at each index until you find one
1458 that satisfies the condition.</p>
1459 <pre>
1460 my( $found, $index ) = ( undef, -1 );
1461 for( $i = 0; $i &lt; @array; $i++ )
1463 if( $array[$i] =~ /Perl/ )
1465 $found = $array[$i];
1466 $index = $i;
1467 last;
1469 }</pre>
1471 </p>
1472 <h2><a name="how_do_i_handle_linked_lists">How do I handle linked lists?</a></h2>
1473 <p>In general, you usually don't need a linked list in Perl, since with
1474 regular arrays, you can push and pop or shift and unshift at either end,
1475 or you can use splice to add and/or remove arbitrary number of elements at
1476 arbitrary points. Both pop and shift are both <code>O(1)</code> operations on Perl's
1477 dynamic arrays. In the absence of shifts and pops, push in general
1478 needs to reallocate on the order every <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_log"><code>log(N)</code></a> times, and unshift will
1479 need to copy pointers each time.</p>
1480 <p>If you really, really wanted, you could use structures as described in
1481 <a href="file://C|\msysgit\mingw\html/pod/perldsc.html">the perldsc manpage</a> or <a href="file://C|\msysgit\mingw\html/pod/perltoot.html">the perltoot manpage</a> and do just what the algorithm book tells you
1482 to do. For example, imagine a list node like this:</p>
1483 <pre>
1484 $node = {
1485 VALUE =&gt; 42,
1486 LINK =&gt; undef,
1487 };</pre>
1488 <p>You could walk the list this way:</p>
1489 <pre>
1490 print &quot;List: &quot;;
1491 for ($node = $head; $node; $node = $node-&gt;{LINK}) {
1492 print $node-&gt;{VALUE}, &quot; &quot;;
1494 print &quot;\n&quot;;</pre>
1495 <p>You could add to the list this way:</p>
1496 <pre>
1497 my ($head, $tail);
1498 $tail = append($head, 1); # grow a new head
1499 for $value ( 2 .. 10 ) {
1500 $tail = append($tail, $value);
1501 }</pre>
1502 <pre>
1503 sub append {
1504 my($list, $value) = @_;
1505 my $node = { VALUE =&gt; $value };
1506 if ($list) {
1507 $node-&gt;{LINK} = $list-&gt;{LINK};
1508 $list-&gt;{LINK} = $node;
1509 } else {
1510 $_[0] = $node; # replace caller's version
1512 return $node;
1513 }</pre>
1514 <p>But again, Perl's built-in are virtually always good enough.</p>
1516 </p>
1517 <h2><a name="how_do_i_handle_circular_lists">How do I handle circular lists?</a></h2>
1518 <p>Circular lists could be handled in the traditional fashion with linked
1519 lists, or you could just do something like this with an array:</p>
1520 <pre>
1521 unshift(@array, pop(@array)); # the last shall be first
1522 push(@array, shift(@array)); # and vice versa</pre>
1524 </p>
1525 <h2><a name="how_do_i_shuffle_an_array_randomly">How do I shuffle an array randomly?</a></h2>
1526 <p>If you either have Perl 5.8.0 or later installed, or if you have
1527 Scalar-List-Utils 1.03 or later installed, you can say:</p>
1528 <pre>
1529 use List::Util 'shuffle';</pre>
1530 <pre>
1531 @shuffled = shuffle(@list);</pre>
1532 <p>If not, you can use a Fisher-Yates shuffle.</p>
1533 <pre>
1534 sub fisher_yates_shuffle {
1535 my $deck = shift; # $deck is a reference to an array
1536 my $i = @$deck;
1537 while (--$i) {
1538 my $j = int rand ($i+1);
1539 @$deck[$i,$j] = @$deck[$j,$i];
1541 }</pre>
1542 <pre>
1543 # shuffle my mpeg collection
1545 my @mpeg = &lt;audio/*/*.mp3&gt;;
1546 fisher_yates_shuffle( \@mpeg ); # randomize @mpeg in place
1547 print @mpeg;</pre>
1548 <p>Note that the above implementation shuffles an array in place,
1549 unlike the List::Util::shuffle() which takes a list and returns
1550 a new shuffled list.</p>
1551 <p>You've probably seen shuffling algorithms that work using splice,
1552 randomly picking another element to swap the current element with</p>
1553 <pre>
1554 srand;
1555 @new = ();
1556 @old = 1 .. 10; # just a demo
1557 while (@old) {
1558 push(@new, splice(@old, rand @old, 1));
1559 }</pre>
1560 <p>This is bad because splice is already O(N), and since you do it N times,
1561 you just invented a quadratic algorithm; that is, O(N**2). This does
1562 not scale, although Perl is so efficient that you probably won't notice
1563 this until you have rather largish arrays.</p>
1565 </p>
1566 <h2><a name="how_do_i_process_modify_each_element_of_an_array">How do I process/modify each element of an array?</a></h2>
1567 <p>Use <code>for</code>/<code>foreach</code>:</p>
1568 <pre>
1569 for (@lines) {
1570 s/foo/bar/; # change that word
1571 tr/XZ/ZX/; # swap those letters
1572 }</pre>
1573 <p>Here's another; let's compute spherical volumes:</p>
1574 <pre>
1575 for (@volumes = @radii) { # @volumes has changed parts
1576 $_ **= 3;
1577 $_ *= (4/3) * 3.14159; # this will be constant folded
1578 }</pre>
1579 <p>which can also be done with <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_map"><code>map()</code></a> which is made to transform
1580 one list into another:</p>
1581 <pre>
1582 @volumes = map {$_ ** 3 * (4/3) * 3.14159} @radii;</pre>
1583 <p>If you want to do the same thing to modify the values of the
1584 hash, you can use the <code>values</code> function. As of Perl 5.6
1585 the values are not copied, so if you modify $orbit (in this
1586 case), you modify the value.</p>
1587 <pre>
1588 for $orbit ( values %orbits ) {
1589 ($orbit **= 3) *= (4/3) * 3.14159;
1590 }</pre>
1591 <p>Prior to perl 5.6 <code>values</code> returned copies of the values,
1592 so older perl code often contains constructions such as
1593 <code>@orbits{keys %orbits}</code> instead of <code>values %orbits</code> where
1594 the hash is to be modified.</p>
1596 </p>
1597 <h2><a name="how_do_i_select_a_random_element_from_an_array">How do I select a random element from an array?</a></h2>
1598 <p>Use the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_rand"><code>rand()</code></a> function (see <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_rand">rand in the perlfunc manpage</a>):</p>
1599 <pre>
1600 $index = rand @array;
1601 $element = $array[$index];</pre>
1602 <p>Or, simply:
1603 my $element = $array[ rand @array ];</p>
1605 </p>
1606 <h2><a name="how_do_i_permute_n_elements_of_a_list">How do I permute N elements of a list?</a></h2>
1607 <p>Use the List::Permutor module on CPAN. If the list is
1608 actually an array, try the Algorithm::Permute module (also
1609 on CPAN). It's written in XS code and is very efficient.</p>
1610 <pre>
1611 use Algorithm::Permute;
1612 my @array = 'a'..'d';
1613 my $p_iterator = Algorithm::Permute-&gt;new ( \@array );
1614 while (my @perm = $p_iterator-&gt;next) {
1615 print &quot;next permutation: (@perm)\n&quot;;
1616 }</pre>
1617 <p>For even faster execution, you could do:</p>
1618 <pre>
1619 use Algorithm::Permute;
1620 my @array = 'a'..'d';
1621 Algorithm::Permute::permute {
1622 print &quot;next permutation: (@array)\n&quot;;
1623 } @array;</pre>
1624 <p>Here's a little program that generates all permutations of
1625 all the words on each line of input. The algorithm embodied
1626 in the <code>permute()</code> function is discussed in Volume 4 (still
1627 unpublished) of Knuth's <em>The Art of Computer Programming</em>
1628 and will work on any list:</p>
1629 <pre>
1630 #!/usr/bin/perl -n
1631 # Fischer-Kause ordered permutation generator</pre>
1632 <pre>
1633 sub permute (&amp;@) {
1634 my $code = shift;
1635 my @idx = 0..$#_;
1636 while ( $code-&gt;(@_[@idx]) ) {
1637 my $p = $#idx;
1638 --$p while $idx[$p-1] &gt; $idx[$p];
1639 my $q = $p or return;
1640 push @idx, reverse splice @idx, $p;
1641 ++$q while $idx[$p-1] &gt; $idx[$q];
1642 @idx[$p-1,$q]=@idx[$q,$p-1];
1644 }</pre>
1645 <pre>
1646 permute {print&quot;@_\n&quot;} split;</pre>
1648 </p>
1649 <h2><a name="how_do_i_sort_an_array_by__anything_">How do I sort an array by (anything)?</a></h2>
1650 <p>Supply a comparison function to <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_sort"><code>sort()</code></a> (described in <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_sort">sort in the perlfunc manpage</a>):</p>
1651 <pre>
1652 @list = sort { $a &lt;=&gt; $b } @list;</pre>
1653 <p>The default sort function is cmp, string comparison, which would
1654 sort <code>(1, 2, 10)</code> into <code>(1, 10, 2)</code>. <code>&lt;=&gt;</code>, used above, is
1655 the numerical comparison operator.</p>
1656 <p>If you have a complicated function needed to pull out the part you
1657 want to sort on, then don't do it inside the sort function. Pull it
1658 out first, because the sort BLOCK can be called many times for the
1659 same element. Here's an example of how to pull out the first word
1660 after the first number on each item, and then sort those words
1661 case-insensitively.</p>
1662 <pre>
1663 @idx = ();
1664 for (@data) {
1665 ($item) = /\d+\s*(\S+)/;
1666 push @idx, uc($item);
1668 @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];</pre>
1669 <p>which could also be written this way, using a trick
1670 that's come to be known as the Schwartzian Transform:</p>
1671 <pre>
1672 @sorted = map { $_-&gt;[0] }
1673 sort { $a-&gt;[1] cmp $b-&gt;[1] }
1674 map { [ $_, uc( (/\d+\s*(\S+)/)[0]) ] } @data;</pre>
1675 <p>If you need to sort on several fields, the following paradigm is useful.</p>
1676 <pre>
1677 @sorted = sort { field1($a) &lt;=&gt; field1($b) ||
1678 field2($a) cmp field2($b) ||
1679 field3($a) cmp field3($b)
1680 } @data;</pre>
1681 <p>This can be conveniently combined with precalculation of keys as given
1682 above.</p>
1683 <p>See the <em>sort</em> article in the ``Far More Than You Ever Wanted
1684 To Know'' collection in <a href="http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz">http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz</a> for
1685 more about this approach.</p>
1686 <p>See also the question below on sorting hashes.</p>
1688 </p>
1689 <h2><a name="how_do_i_manipulate_arrays_of_bits">How do I manipulate arrays of bits?</a></h2>
1690 <p>Use <code>pack()</code> and unpack(), or else <code>vec()</code> and the bitwise operations.</p>
1691 <p>For example, this sets $vec to have bit N set if $ints[N] was set:</p>
1692 <pre>
1693 $vec = '';
1694 foreach(@ints) { vec($vec,$_,1) = 1 }</pre>
1695 <p>Here's how, given a vector in $vec, you can
1696 get those bits into your @ints array:</p>
1697 <pre>
1698 sub bitvec_to_list {
1699 my $vec = shift;
1700 my @ints;
1701 # Find null-byte density then select best algorithm
1702 if ($vec =~ tr/\0// / length $vec &gt; 0.95) {
1703 use integer;
1704 my $i;
1705 # This method is faster with mostly null-bytes
1706 while($vec =~ /[^\0]/g ) {
1707 $i = -9 + 8 * pos $vec;
1708 push @ints, $i if vec($vec, ++$i, 1);
1709 push @ints, $i if vec($vec, ++$i, 1);
1710 push @ints, $i if vec($vec, ++$i, 1);
1711 push @ints, $i if vec($vec, ++$i, 1);
1712 push @ints, $i if vec($vec, ++$i, 1);
1713 push @ints, $i if vec($vec, ++$i, 1);
1714 push @ints, $i if vec($vec, ++$i, 1);
1715 push @ints, $i if vec($vec, ++$i, 1);
1717 } else {
1718 # This method is a fast general algorithm
1719 use integer;
1720 my $bits = unpack &quot;b*&quot;, $vec;
1721 push @ints, 0 if $bits =~ s/^(\d)// &amp;&amp; $1;
1722 push @ints, pos $bits while($bits =~ /1/g);
1724 return \@ints;
1725 }</pre>
1726 <p>This method gets faster the more sparse the bit vector is.
1727 (Courtesy of Tim Bunce and Winfried Koenig.)</p>
1728 <p>You can make the while loop a lot shorter with this suggestion
1729 from Benjamin Goldberg:</p>
1730 <pre>
1731 while($vec =~ /[^\0]+/g ) {
1732 push @ints, grep vec($vec, $_, 1), $-[0] * 8 .. $+[0] * 8;
1733 }</pre>
1734 <p>Or use the CPAN module Bit::Vector:</p>
1735 <pre>
1736 $vector = Bit::Vector-&gt;new($num_of_bits);
1737 $vector-&gt;Index_List_Store(@ints);
1738 @ints = $vector-&gt;Index_List_Read();</pre>
1739 <p>Bit::Vector provides efficient methods for bit vector, sets of small integers
1740 and ``big int'' math.</p>
1741 <p>Here's a more extensive illustration using vec():</p>
1742 <pre>
1743 # vec demo
1744 $vector = &quot;\xff\x0f\xef\xfe&quot;;
1745 print &quot;Ilya's string \\xff\\x0f\\xef\\xfe represents the number &quot;,
1746 unpack(&quot;N&quot;, $vector), &quot;\n&quot;;
1747 $is_set = vec($vector, 23, 1);
1748 print &quot;Its 23rd bit is &quot;, $is_set ? &quot;set&quot; : &quot;clear&quot;, &quot;.\n&quot;;
1749 pvec($vector);</pre>
1750 <pre>
1751 set_vec(1,1,1);
1752 set_vec(3,1,1);
1753 set_vec(23,1,1);</pre>
1754 <pre>
1755 set_vec(3,1,3);
1756 set_vec(3,2,3);
1757 set_vec(3,4,3);
1758 set_vec(3,4,7);
1759 set_vec(3,8,3);
1760 set_vec(3,8,7);</pre>
1761 <pre>
1762 set_vec(0,32,17);
1763 set_vec(1,32,17);</pre>
1764 <pre>
1765 sub set_vec {
1766 my ($offset, $width, $value) = @_;
1767 my $vector = '';
1768 vec($vector, $offset, $width) = $value;
1769 print &quot;offset=$offset width=$width value=$value\n&quot;;
1770 pvec($vector);
1771 }</pre>
1772 <pre>
1773 sub pvec {
1774 my $vector = shift;
1775 my $bits = unpack(&quot;b*&quot;, $vector);
1776 my $i = 0;
1777 my $BASE = 8;</pre>
1778 <pre>
1779 print &quot;vector length in bytes: &quot;, length($vector), &quot;\n&quot;;
1780 @bytes = unpack(&quot;A8&quot; x length($vector), $bits);
1781 print &quot;bits are: @bytes\n\n&quot;;
1782 }</pre>
1784 </p>
1785 <h2><a name="why_does_defined___return_true_on_empty_arrays_and_hashes">Why does <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_defined"><code>defined()</code></a> return true on empty arrays and hashes?</a></h2>
1786 <p>The short story is that you should probably only use defined on scalars or
1787 functions, not on aggregates (arrays and hashes). See <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_defined">defined in the perlfunc manpage</a>
1788 in the 5.004 release or later of Perl for more detail.</p>
1790 </p>
1791 <hr />
1792 <h1><a name="data__hashes__associative_arrays_">Data: Hashes (Associative Arrays)</a></h1>
1794 </p>
1795 <h2><a name="how_do_i_process_an_entire_hash">How do I process an entire hash?</a></h2>
1796 <p>Use the <code>each()</code> function (see <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#each">each in the perlfunc manpage</a>) if you don't care
1797 whether it's sorted:</p>
1798 <pre>
1799 while ( ($key, $value) = each %hash) {
1800 print &quot;$key = $value\n&quot;;
1801 }</pre>
1802 <p>If you want it sorted, you'll have to use <code>foreach()</code> on the result of
1803 sorting the keys as shown in an earlier question.</p>
1805 </p>
1806 <h2><a name="what_happens_if_i_add_or_remove_keys_from_a_hash_while_iterating_over_it">What happens if I add or remove keys from a hash while iterating over it?</a></h2>
1807 <p>(contributed by brian d foy)</p>
1808 <p>The easy answer is ``Don't do that!''</p>
1809 <p>If you iterate through the hash with each(), you can delete the key
1810 most recently returned without worrying about it. If you delete or add
1811 other keys, the iterator may skip or double up on them since perl
1812 may rearrange the hash table. See the
1813 entry for <code>each()</code> in <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html">the perlfunc manpage</a>.</p>
1815 </p>
1816 <h2><a name="how_do_i_look_up_a_hash_element_by_value">How do I look up a hash element by value?</a></h2>
1817 <p>Create a reverse hash:</p>
1818 <pre>
1819 %by_value = reverse %by_key;
1820 $key = $by_value{$value};</pre>
1821 <p>That's not particularly efficient. It would be more space-efficient
1822 to use:</p>
1823 <pre>
1824 while (($key, $value) = each %by_key) {
1825 $by_value{$value} = $key;
1826 }</pre>
1827 <p>If your hash could have repeated values, the methods above will only find
1828 one of the associated keys. This may or may not worry you. If it does
1829 worry you, you can always reverse the hash into a hash of arrays instead:</p>
1830 <pre>
1831 while (($key, $value) = each %by_key) {
1832 push @{$key_list_by_value{$value}}, $key;
1833 }</pre>
1835 </p>
1836 <h2><a name="how_can_i_know_how_many_entries_are_in_a_hash">How can I know how many entries are in a hash?</a></h2>
1837 <p>If you mean how many keys, then all you have to do is
1838 use the <code>keys()</code> function in a scalar context:</p>
1839 <pre>
1840 $num_keys = keys %hash;</pre>
1841 <p>The <code>keys()</code> function also resets the iterator, which means that you may
1842 see strange results if you use this between uses of other hash operators
1843 such as each().</p>
1845 </p>
1846 <h2><a name="how_do_i_sort_a_hash__optionally_by_value_instead_of_key_">How do I sort a hash (optionally by value instead of key)?</a></h2>
1847 <p>(contributed by brian d foy)</p>
1848 <p>To sort a hash, start with the keys. In this example, we give the list of
1849 keys to the sort function which then compares them ASCIIbetically (which
1850 might be affected by your locale settings). The output list has the keys
1851 in ASCIIbetical order. Once we have the keys, we can go through them to
1852 create a report which lists the keys in ASCIIbetical order.</p>
1853 <pre>
1854 my @keys = sort { $a cmp $b } keys %hash;</pre>
1855 <pre>
1856 foreach my $key ( @keys )
1858 printf &quot;%-20s %6d\n&quot;, $key, $hash{$value};
1859 }</pre>
1860 <p>We could get more fancy in the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_sort"><code>sort()</code></a> block though. Instead of
1861 comparing the keys, we can compute a value with them and use that
1862 value as the comparison.</p>
1863 <p>For instance, to make our report order case-insensitive, we use
1864 the <code>\L</code> sequence in a double-quoted string to make everything
1865 lowercase. The <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_sort"><code>sort()</code></a> block then compares the lowercased
1866 values to determine in which order to put the keys.</p>
1867 <pre>
1868 my @keys = sort { &quot;\L$a&quot; cmp &quot;\L$b&quot; } keys %hash;</pre>
1869 <p>Note: if the computation is expensive or the hash has many elements,
1870 you may want to look at the Schwartzian Transform to cache the
1871 computation results.</p>
1872 <p>If we want to sort by the hash value instead, we use the hash key
1873 to look it up. We still get out a list of keys, but this time they
1874 are ordered by their value.</p>
1875 <pre>
1876 my @keys = sort { $hash{$a} &lt;=&gt; $hash{$b} } keys %hash;</pre>
1877 <p>From there we can get more complex. If the hash values are the same,
1878 we can provide a secondary sort on the hash key.</p>
1879 <pre>
1880 my @keys = sort {
1881 $hash{$a} &lt;=&gt; $hash{$b}
1883 &quot;\L$a&quot; cmp &quot;\L$b&quot;
1884 } keys %hash;</pre>
1886 </p>
1887 <h2><a name="how_can_i_always_keep_my_hash_sorted">How can I always keep my hash sorted?</a></h2>
1888 <p>You can look into using the DB_File module and <code>tie()</code> using the
1889 $DB_BTREE hash bindings as documented in <a href="file://C|\msysgit\mingw\html/ext/DB_File/in_memory_databases.html">In Memory Databases in the DB_File manpage</a>.
1890 The Tie::IxHash module from CPAN might also be instructive.</p>
1892 </p>
1893 <h2><a name="what_s_the_difference_between_delete_and_undef_with_hashes">What's the difference between ``delete'' and ``undef'' with hashes?</a></h2>
1894 <p>Hashes contain pairs of scalars: the first is the key, the
1895 second is the value. The key will be coerced to a string,
1896 although the value can be any kind of scalar: string,
1897 number, or reference. If a key $key is present in
1898 %hash, <code>exists($hash{$key})</code> will return true. The value
1899 for a given key can be <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_undef"><code>undef</code></a>, in which case
1900 <code>$hash{$key}</code> will be <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_undef"><code>undef</code></a> while <code>exists $hash{$key}</code>
1901 will return true. This corresponds to (<code>$key</code>, <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_undef"><code>undef</code></a>)
1902 being in the hash.</p>
1903 <p>Pictures help... here's the %hash table:</p>
1904 <pre>
1905 keys values
1906 +------+------+
1907 | a | 3 |
1908 | x | 7 |
1909 | d | 0 |
1910 | e | 2 |
1911 +------+------+</pre>
1912 <p>And these conditions hold</p>
1913 <pre>
1914 $hash{'a'} is true
1915 $hash{'d'} is false
1916 defined $hash{'d'} is true
1917 defined $hash{'a'} is true
1918 exists $hash{'a'} is true (Perl5 only)
1919 grep ($_ eq 'a', keys %hash) is true</pre>
1920 <p>If you now say</p>
1921 <pre>
1922 undef $hash{'a'}</pre>
1923 <p>your table now reads:</p>
1924 <pre>
1925 keys values
1926 +------+------+
1927 | a | undef|
1928 | x | 7 |
1929 | d | 0 |
1930 | e | 2 |
1931 +------+------+</pre>
1932 <p>and these conditions now hold; changes in caps:</p>
1933 <pre>
1934 $hash{'a'} is FALSE
1935 $hash{'d'} is false
1936 defined $hash{'d'} is true
1937 defined $hash{'a'} is FALSE
1938 exists $hash{'a'} is true (Perl5 only)
1939 grep ($_ eq 'a', keys %hash) is true</pre>
1940 <p>Notice the last two: you have an undef value, but a defined key!</p>
1941 <p>Now, consider this:</p>
1942 <pre>
1943 delete $hash{'a'}</pre>
1944 <p>your table now reads:</p>
1945 <pre>
1946 keys values
1947 +------+------+
1948 | x | 7 |
1949 | d | 0 |
1950 | e | 2 |
1951 +------+------+</pre>
1952 <p>and these conditions now hold; changes in caps:</p>
1953 <pre>
1954 $hash{'a'} is false
1955 $hash{'d'} is false
1956 defined $hash{'d'} is true
1957 defined $hash{'a'} is false
1958 exists $hash{'a'} is FALSE (Perl5 only)
1959 grep ($_ eq 'a', keys %hash) is FALSE</pre>
1960 <p>See, the whole entry is gone!</p>
1962 </p>
1963 <h2><a name="why_don_t_my_tied_hashes_make_the_defined_exists_distinction">Why don't my tied hashes make the defined/exists distinction?</a></h2>
1964 <p>This depends on the tied hash's implementation of EXISTS().
1965 For example, there isn't the concept of undef with hashes
1966 that are tied to DBM* files. It also means that <code>exists()</code> and
1967 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_defined"><code>defined()</code></a> do the same thing with a DBM* file, and what they
1968 end up doing is not what they do with ordinary hashes.</p>
1970 </p>
1971 <h2><a name="how_do_i_reset_an_each___operation_partway_through">How do I reset an <code>each()</code> operation part-way through?</a></h2>
1972 <p>Using <code>keys %hash</code> in scalar context returns the number of keys in
1973 the hash <em>and</em> resets the iterator associated with the hash. You may
1974 need to do this if you use <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_last"><code>last</code></a> to exit a loop early so that when you
1975 re-enter it, the hash iterator has been reset.</p>
1977 </p>
1978 <h2><a name="how_can_i_get_the_unique_keys_from_two_hashes">How can I get the unique keys from two hashes?</a></h2>
1979 <p>First you extract the keys from the hashes into lists, then solve
1980 the ``removing duplicates'' problem described above. For example:</p>
1981 <pre>
1982 %seen = ();
1983 for $element (keys(%foo), keys(%bar)) {
1984 $seen{$element}++;
1986 @uniq = keys %seen;</pre>
1987 <p>Or more succinctly:</p>
1988 <pre>
1989 @uniq = keys %{{%foo,%bar}};</pre>
1990 <p>Or if you really want to save space:</p>
1991 <pre>
1992 %seen = ();
1993 while (defined ($key = each %foo)) {
1994 $seen{$key}++;
1996 while (defined ($key = each %bar)) {
1997 $seen{$key}++;
1999 @uniq = keys %seen;</pre>
2001 </p>
2002 <h2><a name="how_can_i_store_a_multidimensional_array_in_a_dbm_file">How can I store a multidimensional array in a DBM file?</a></h2>
2003 <p>Either stringify the structure yourself (no fun), or else
2004 get the MLDBM (which uses Data::Dumper) module from CPAN and layer
2005 it on top of either DB_File or GDBM_File.</p>
2007 </p>
2008 <h2><a name="how_can_i_make_my_hash_remember_the_order_i_put_elements_into_it">How can I make my hash remember the order I put elements into it?</a></h2>
2009 <p>Use the Tie::IxHash from CPAN.</p>
2010 <pre>
2011 use Tie::IxHash;
2012 tie my %myhash, 'Tie::IxHash';
2013 for (my $i=0; $i&lt;20; $i++) {
2014 $myhash{$i} = 2*$i;
2016 my @keys = keys %myhash;
2017 # @keys = (0,1,2,3,...)</pre>
2019 </p>
2020 <h2><a name="why_does_passing_a_subroutine_an_undefined_element_in_a_hash_create_it">Why does passing a subroutine an undefined element in a hash create it?</a></h2>
2021 <p>If you say something like:</p>
2022 <pre>
2023 somefunc($hash{&quot;nonesuch key here&quot;});</pre>
2024 <p>Then that element ``autovivifies''; that is, it springs into existence
2025 whether you store something there or not. That's because functions
2026 get scalars passed in by reference. If <code>somefunc()</code> modifies <code>$_[0]</code>,
2027 it has to be ready to write it back into the caller's version.</p>
2028 <p>This has been fixed as of Perl5.004.</p>
2029 <p>Normally, merely accessing a key's value for a nonexistent key does
2030 <em>not</em> cause that key to be forever there. This is different than
2031 awk's behavior.</p>
2033 </p>
2034 <h2><a name="how_can_i_make_the_perl_equivalent_of_a_c_structure_c___class_hash_or_array_of_hashes_or_arrays">How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?</a></h2>
2035 <p>Usually a hash ref, perhaps like this:</p>
2036 <pre>
2037 $record = {
2038 NAME =&gt; &quot;Jason&quot;,
2039 EMPNO =&gt; 132,
2040 TITLE =&gt; &quot;deputy peon&quot;,
2041 AGE =&gt; 23,
2042 SALARY =&gt; 37_000,
2043 PALS =&gt; [ &quot;Norbert&quot;, &quot;Rhys&quot;, &quot;Phineas&quot;],
2044 };</pre>
2045 <p>References are documented in <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a> and the upcoming <a href="file://C|\msysgit\mingw\html/pod/perlreftut.html">the perlreftut manpage</a>.
2046 Examples of complex data structures are given in <a href="file://C|\msysgit\mingw\html/pod/perldsc.html">the perldsc manpage</a> and
2047 <a href="file://C|\msysgit\mingw\html/pod/perllol.html">the perllol manpage</a>. Examples of structures and object-oriented classes are
2048 in <a href="file://C|\msysgit\mingw\html/pod/perltoot.html">the perltoot manpage</a>.</p>
2050 </p>
2051 <h2><a name="how_can_i_use_a_reference_as_a_hash_key">How can I use a reference as a hash key?</a></h2>
2052 <p>(contributed by brian d foy)</p>
2053 <p>Hash keys are strings, so you can't really use a reference as the key.
2054 When you try to do that, perl turns the reference into its stringified
2055 form (for instance, <code>HASH(0xDEADBEEF)</code>). From there you can't get back
2056 the reference from the stringified form, at least without doing some
2057 extra work on your own. Also remember that hash keys must be unique, but
2058 two different variables can store the same reference (and those variables
2059 can change later).</p>
2060 <p>The Tie::RefHash module, which is distributed with perl, might be what
2061 you want. It handles that extra work.</p>
2063 </p>
2064 <hr />
2065 <h1><a name="data__misc">Data: Misc</a></h1>
2067 </p>
2068 <h2><a name="how_do_i_handle_binary_data_correctly">How do I handle binary data correctly?</a></h2>
2069 <p>Perl is binary clean, so this shouldn't be a problem. For example,
2070 this works fine (assuming the files are found):</p>
2071 <pre>
2072 if (`cat /vmunix` =~ /gzip/) {
2073 print &quot;Your kernel is GNU-zip enabled!\n&quot;;
2074 }</pre>
2075 <p>On less elegant (read: Byzantine) systems, however, you have
2076 to play tedious games with ``text'' versus ``binary'' files. See
2077 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_binmode">binmode in the perlfunc manpage</a> or <a href="file://C|\msysgit\mingw\html/pod/perlopentut.html">the perlopentut manpage</a>.</p>
2078 <p>If you're concerned about 8-bit ASCII data, then see <a href="file://C|\msysgit\mingw\html/pod/perllocale.html">the perllocale manpage</a>.</p>
2079 <p>If you want to deal with multibyte characters, however, there are
2080 some gotchas. See the section on Regular Expressions.</p>
2082 </p>
2083 <h2><a name="how_do_i_determine_whether_a_scalar_is_a_number_whole_integer_float">How do I determine whether a scalar is a number/whole/integer/float?</a></h2>
2084 <p>Assuming that you don't care about IEEE notations like ``NaN'' or
2085 ``Infinity'', you probably just want to use a regular expression.</p>
2086 <pre>
2087 if (/\D/) { print &quot;has nondigits\n&quot; }
2088 if (/^\d+$/) { print &quot;is a whole number\n&quot; }
2089 if (/^-?\d+$/) { print &quot;is an integer\n&quot; }
2090 if (/^[+-]?\d+$/) { print &quot;is a +/- integer\n&quot; }
2091 if (/^-?\d+\.?\d*$/) { print &quot;is a real number\n&quot; }
2092 if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) { print &quot;is a decimal number\n&quot; }
2093 if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/)
2094 { print &quot;a C float\n&quot; }</pre>
2095 <p>There are also some commonly used modules for the task.
2096 <a href="file://C|\msysgit\mingw\html/lib/Scalar/Util.html">the Scalar::Util manpage</a> (distributed with 5.8) provides access to perl's
2097 internal function <code>looks_like_number</code> for determining
2098 whether a variable looks like a number. <a href="file://C|\msysgit\mingw\html/Data/Types.html">the Data::Types manpage</a>
2099 exports functions that validate data types using both the
2100 above and other regular expressions. Thirdly, there is
2101 <code>Regexp::Common</code> which has regular expressions to match
2102 various types of numbers. Those three modules are available
2103 from the CPAN.</p>
2104 <p>If you're on a POSIX system, Perl supports the <code>POSIX::strtod</code>
2105 function. Its semantics are somewhat cumbersome, so here's a <code>getnum</code>
2106 wrapper function for more convenient access. This function takes
2107 a string and returns the number it found, or <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_undef"><code>undef</code></a> for input that
2108 isn't a C float. The <code>is_numeric</code> function is a front end to <code>getnum</code>
2109 if you just want to say, ``Is this a float?''</p>
2110 <pre>
2111 sub getnum {
2112 use POSIX qw(strtod);
2113 my $str = shift;
2114 $str =~ s/^\s+//;
2115 $str =~ s/\s+$//;
2116 $! = 0;
2117 my($num, $unparsed) = strtod($str);
2118 if (($str eq '') || ($unparsed != 0) || $!) {
2119 return undef;
2120 } else {
2121 return $num;
2123 }</pre>
2124 <pre>
2125 sub is_numeric { defined getnum($_[0]) }</pre>
2126 <p>Or you could check out the <a href="file://C|\msysgit\mingw\html/String/Scanf.html">the String::Scanf manpage</a> module on the CPAN
2127 instead. The POSIX module (part of the standard Perl distribution) provides
2128 the <code>strtod</code> and <code>strtol</code> for converting strings to double and longs,
2129 respectively.</p>
2131 </p>
2132 <h2><a name="how_do_i_keep_persistent_data_across_program_calls">How do I keep persistent data across program calls?</a></h2>
2133 <p>For some specific applications, you can use one of the DBM modules.
2134 See <a href="file://C|\msysgit\mingw\html/lib/AnyDBM_File.html">the AnyDBM_File manpage</a>. More generically, you should consult the FreezeThaw
2135 or Storable modules from CPAN. Starting from Perl 5.8 Storable is part
2136 of the standard distribution. Here's one example using Storable's <code>store</code>
2137 and <code>retrieve</code> functions:</p>
2138 <pre>
2139 use Storable;
2140 store(\%hash, &quot;filename&quot;);</pre>
2141 <pre>
2142 # later on...
2143 $href = retrieve(&quot;filename&quot;); # by ref
2144 %hash = %{ retrieve(&quot;filename&quot;) }; # direct to hash</pre>
2146 </p>
2147 <h2><a name="how_do_i_print_out_or_copy_a_recursive_data_structure">How do I print out or copy a recursive data structure?</a></h2>
2148 <p>The Data::Dumper module on CPAN (or the 5.005 release of Perl) is great
2149 for printing out data structures. The Storable module on CPAN (or the
2150 5.8 release of Perl), provides a function called <code>dclone</code> that recursively
2151 copies its argument.</p>
2152 <pre>
2153 use Storable qw(dclone);
2154 $r2 = dclone($r1);</pre>
2155 <p>Where $r1 can be a reference to any kind of data structure you'd like.
2156 It will be deeply copied. Because <code>dclone</code> takes and returns references,
2157 you'd have to add extra punctuation if you had a hash of arrays that
2158 you wanted to copy.</p>
2159 <pre>
2160 %newhash = %{ dclone(\%oldhash) };</pre>
2162 </p>
2163 <h2><a name="how_do_i_define_methods_for_every_class_object">How do I define methods for every class/object?</a></h2>
2164 <p>Use the UNIVERSAL class (see <a href="file://C|\msysgit\mingw\html/lib/UNIVERSAL.html">the UNIVERSAL manpage</a>).</p>
2166 </p>
2167 <h2><a name="how_do_i_verify_a_credit_card_checksum">How do I verify a credit card checksum?</a></h2>
2168 <p>Get the Business::CreditCard module from CPAN.</p>
2170 </p>
2171 <h2><a name="how_do_i_pack_arrays_of_doubles_or_floats_for_xs_code">How do I pack arrays of doubles or floats for XS code?</a></h2>
2172 <p>The kgbpack.c code in the PGPLOT module on CPAN does just this.
2173 If you're doing a lot of float or double processing, consider using
2174 the PDL module from CPAN instead--it makes number-crunching easy.</p>
2176 </p>
2177 <hr />
2178 <h1><a name="author_and_copyright">AUTHOR AND COPYRIGHT</a></h1>
2179 <p>Copyright (c) 1997-2006 Tom Christiansen, Nathan Torkington, and
2180 other authors as noted. All rights reserved.</p>
2181 <p>This documentation is free; you can redistribute it and/or modify it
2182 under the same terms as Perl itself.</p>
2183 <p>Irrespective of its distribution, all code examples in this file
2184 are hereby placed into the public domain. You are permitted and
2185 encouraged to use this code in your own programs for fun
2186 or for profit as you see fit. A simple comment in the code giving
2187 credit would be courteous but is not required.</p>
2188 <table border="0" width="100%" cellspacing="0" cellpadding="3">
2189 <tr><td class="block" style="background-color: #cccccc" valign="middle">
2190 <big><strong><span class="block">&nbsp;perlfaq4 - Data Manipulation</span></strong></big>
2191 </td></tr>
2192 </table>
2194 </body>
2196 </html>