Install Perl 5.8.8
[msysgit.git] / mingw / html / pod / perlfaq7.html
blob3fdba26d7706c5d65d915af4ed0a889fd458f09c
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>perlfaq7 - General Perl Language Issues</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;perlfaq7 - General Perl Language Issues</span></strong></big>
14 </td></tr>
15 </table>
17 <p><a name="__index__"></a></p>
18 <!-- INDEX BEGIN -->
20 <ul>
22 <li><a href="#name">NAME</a></li>
23 <li><a href="#description">DESCRIPTION</a></li>
24 <ul>
26 <li><a href="#can_i_get_a_bnf_yacc_re_for_the_perl_language">Can I get a BNF/yacc/RE for the Perl language?</a></li>
27 <li><a href="#what_are_all_these_______punctuation_signs__and_how_do_i_know_when_to_use_them">What are all these $@%&amp;* punctuation signs, and how do I know when to use them?</a></li>
28 <li><a href="#do_i_always_never_have_to_quote_my_strings_or_use_semicolons_and_commas">Do I always/never have to quote my strings or use semicolons and commas?</a></li>
29 <li><a href="#how_do_i_skip_some_return_values">How do I skip some return values?</a></li>
30 <li><a href="#how_do_i_temporarily_block_warnings">How do I temporarily block warnings?</a></li>
31 <li><a href="#what_s_an_extension">What's an extension?</a></li>
32 <li><a href="#why_do_perl_operators_have_different_precedence_than_c_operators">Why do Perl operators have different precedence than C operators?</a></li>
33 <li><a href="#how_do_i_declare_create_a_structure">How do I declare/create a structure?</a></li>
34 <li><a href="#how_do_i_create_a_module">How do I create a module?</a></li>
35 <li><a href="#how_do_i_create_a_class">How do I create a class?</a></li>
36 <li><a href="#how_can_i_tell_if_a_variable_is_tainted">How can I tell if a variable is tainted?</a></li>
37 <li><a href="#what_s_a_closure">What's a closure?</a></li>
38 <li><a href="#what_is_variable_suicide_and_how_can_i_prevent_it">What is variable suicide and how can I prevent it?</a></li>
39 <li><a href="#how_can_i_pass_return_a__function__filehandle__array__hash__method__regex_">How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?</a></li>
40 <li><a href="#how_do_i_create_a_static_variable">How do I create a static variable?</a></li>
41 <li><a href="#what_s_the_difference_between_dynamic_and_lexical__static__scoping_between_local___and_my__">What's the difference between dynamic and lexical (static) scoping? Between <code>local()</code> and my()?</a></li>
42 <li><a href="#how_can_i_access_a_dynamic_variable_while_a_similarly_named_lexical_is_in_scope">How can I access a dynamic variable while a similarly named lexical is in scope?</a></li>
43 <li><a href="#what_s_the_difference_between_deep_and_shallow_binding">What's the difference between deep and shallow binding?</a></li>
44 <li><a href="#why_doesn_t_my__foo_____file___work_right">Why doesn't ``my($foo) = &lt;FILE&gt;;'' work right?</a></li>
45 <li><a href="#how_do_i_redefine_a_builtin_function__operator__or_method">How do I redefine a builtin function, operator, or method?</a></li>
46 <li><a href="#what_s_the_difference_between_calling_a_function_as__foo_and_foo__">What's the difference between calling a function as &amp;foo and foo()?</a></li>
47 <li><a href="#how_do_i_create_a_switch_or_case_statement">How do I create a switch or case statement?</a></li>
48 <li><a href="#how_can_i_catch_accesses_to_undefined_variables__functions__or_methods">How can I catch accesses to undefined variables, functions, or methods?</a></li>
49 <li><a href="#why_can_t_a_method_included_in_this_same_file_be_found">Why can't a method included in this same file be found?</a></li>
50 <li><a href="#how_can_i_find_out_my_current_package">How can I find out my current package?</a></li>
51 <li><a href="#how_can_i_comment_out_a_large_block_of_perl_code">How can I comment out a large block of perl code?</a></li>
52 <li><a href="#how_do_i_clear_a_package">How do I clear a package?</a></li>
53 <li><a href="#how_can_i_use_a_variable_as_a_variable_name">How can I use a variable as a variable name?</a></li>
54 <li><a href="#what_does_bad_interpreter_mean">What does ``bad interpreter'' mean?</a></li>
55 </ul>
57 <li><a href="#author_and_copyright">AUTHOR AND COPYRIGHT</a></li>
58 </ul>
59 <!-- INDEX END -->
61 <hr />
62 <p>
63 </p>
64 <h1><a name="name">NAME</a></h1>
65 <p>perlfaq7 - General Perl Language Issues ($Revision: 1.28 $, $Date: 2005/12/31 00:54:37 $)</p>
66 <p>
67 </p>
68 <hr />
69 <h1><a name="description">DESCRIPTION</a></h1>
70 <p>This section deals with general Perl language issues that don't
71 clearly fit into any of the other sections.</p>
72 <p>
73 </p>
74 <h2><a name="can_i_get_a_bnf_yacc_re_for_the_perl_language">Can I get a BNF/yacc/RE for the Perl language?</a></h2>
75 <p>There is no BNF, but you can paw your way through the yacc grammar in
76 perly.y in the source distribution if you're particularly brave. The
77 grammar relies on very smart tokenizing code, so be prepared to
78 venture into toke.c as well.</p>
79 <p>In the words of Chaim Frenkel: ``Perl's grammar can not be reduced to BNF.
80 The work of parsing perl is distributed between yacc, the lexer, smoke
81 and mirrors.''</p>
82 <p>
83 </p>
84 <h2><a name="what_are_all_these_______punctuation_signs__and_how_do_i_know_when_to_use_them">What are all these $@%&amp;* punctuation signs, and how do I know when to use them?</a></h2>
85 <p>They are type specifiers, as detailed in <a href="file://C|\msysgit\mingw\html/pod/perldata.html">the perldata manpage</a>:</p>
86 <pre>
87 $ for scalar values (number, string or reference)
88 @ for arrays
89 % for hashes (associative arrays)
90 &amp; for subroutines (aka functions, procedures, methods)
91 * for all types of that symbol name. In version 4 you used them like
92 pointers, but in modern perls you can just use references.</pre>
93 <p>There are couple of other symbols that you're likely to encounter that aren't
94 really type specifiers:</p>
95 <pre>
96 &lt;&gt; are used for inputting a record from a filehandle.
97 \ takes a reference to something.</pre>
98 <p>Note that &lt;FILE&gt; is <em>neither</em> the type specifier for files
99 nor the name of the handle. It is the <code>&lt;&gt;</code> operator applied
100 to the handle FILE. It reads one line (well, record--see
101 <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#_e_sol_">$&sol; in the perlvar manpage</a>) from the handle FILE in scalar context, or <em>all</em> lines
102 in list context. When performing open, close, or any other operation
103 besides <code>&lt;&gt;</code> on files, or even when talking about the handle, do
104 <em>not</em> use the brackets. These are correct: <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_eof"><code>eof(FH)</code></a>, <code>seek(FH, 0,
105 2)</code> and ``copying from STDIN to FILE''.</p>
107 </p>
108 <h2><a name="do_i_always_never_have_to_quote_my_strings_or_use_semicolons_and_commas">Do I always/never have to quote my strings or use semicolons and commas?</a></h2>
109 <p>Normally, a bareword doesn't need to be quoted, but in most cases
110 probably should be (and must be under <code>use strict</code>). But a hash key
111 consisting of a simple word (that isn't the name of a defined
112 subroutine) and the left-hand operand to the <code>=&gt;</code> operator both
113 count as though they were quoted:</p>
114 <pre>
115 This is like this
116 ------------ ---------------
117 $foo{line} $foo{'line'}
118 bar =&gt; stuff 'bar' =&gt; stuff</pre>
119 <p>The final semicolon in a block is optional, as is the final comma in a
120 list. Good style (see <a href="file://C|\msysgit\mingw\html/pod/perlstyle.html">the perlstyle manpage</a>) says to put them in except for
121 one-liners:</p>
122 <pre>
123 if ($whoops) { exit 1 }
124 @nums = (1, 2, 3);</pre>
125 <pre>
126 if ($whoops) {
127 exit 1;
129 @lines = (
130 &quot;There Beren came from mountains cold&quot;,
131 &quot;And lost he wandered under leaves&quot;,
132 );</pre>
134 </p>
135 <h2><a name="how_do_i_skip_some_return_values">How do I skip some return values?</a></h2>
136 <p>One way is to treat the return values as a list and index into it:</p>
137 <pre>
138 $dir = (getpwnam($user))[7];</pre>
139 <p>Another way is to use undef as an element on the left-hand-side:</p>
140 <pre>
141 ($dev, $ino, undef, undef, $uid, $gid) = stat($file);</pre>
142 <p>You can also use a list slice to select only the elements that
143 you need:</p>
144 <pre>
145 ($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5];</pre>
147 </p>
148 <h2><a name="how_do_i_temporarily_block_warnings">How do I temporarily block warnings?</a></h2>
149 <p>If you are running Perl 5.6.0 or better, the <code>use warnings</code> pragma
150 allows fine control of what warning are produced.
151 See <a href="file://C|\msysgit\mingw\html/pod/perllexwarn.html">the perllexwarn manpage</a> for more details.</p>
152 <pre>
154 no warnings; # temporarily turn off warnings
155 $a = $b + $c; # I know these might be undef
156 }</pre>
157 <p>Additionally, you can enable and disable categories of warnings.
158 You turn off the categories you want to ignore and you can still
159 get other categories of warnings. See <a href="file://C|\msysgit\mingw\html/pod/perllexwarn.html">the perllexwarn manpage</a> for the
160 complete details, including the category names and hierarchy.</p>
161 <pre>
163 no warnings 'uninitialized';
164 $a = $b + $c;
165 }</pre>
166 <p>If you have an older version of Perl, the <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___w"><code>$^W</code></a> variable (documented
167 in <a href="file://C|\msysgit\mingw\html/pod/perlvar.html">the perlvar manpage</a>) controls runtime warnings for a block:</p>
168 <pre>
170 local $^W = 0; # temporarily turn off warnings
171 $a = $b + $c; # I know these might be undef
172 }</pre>
173 <p>Note that like all the punctuation variables, you cannot currently
174 use <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my()</code></a> on <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___w"><code>$^W</code></a>, only local().</p>
176 </p>
177 <h2><a name="what_s_an_extension">What's an extension?</a></h2>
178 <p>An extension is a way of calling compiled C code from Perl. Reading
179 <a href="file://C|\msysgit\mingw\html/pod/perlxstut.html">the perlxstut manpage</a> is a good place to learn more about extensions.</p>
181 </p>
182 <h2><a name="why_do_perl_operators_have_different_precedence_than_c_operators">Why do Perl operators have different precedence than C operators?</a></h2>
183 <p>Actually, they don't. All C operators that Perl copies have the same
184 precedence in Perl as they do in C. The problem is with operators that C
185 doesn't have, especially functions that give a list context to everything
186 on their right, eg. print, chmod, exec, and so on. Such functions are
187 called ``list operators'' and appear as such in the precedence table in
188 <a href="file://C|\msysgit\mingw\html/pod/perlop.html">the perlop manpage</a>.</p>
189 <p>A common mistake is to write:</p>
190 <pre>
191 unlink $file || die &quot;snafu&quot;;</pre>
192 <p>This gets interpreted as:</p>
193 <pre>
194 unlink ($file || die &quot;snafu&quot;);</pre>
195 <p>To avoid this problem, either put in extra parentheses or use the
196 super low precedence <code>or</code> operator:</p>
197 <pre>
198 (unlink $file) || die &quot;snafu&quot;;
199 unlink $file or die &quot;snafu&quot;;</pre>
200 <p>The ``English'' operators (<code>and</code>, <code>or</code>, <code>xor</code>, and <code>not</code>)
201 deliberately have precedence lower than that of list operators for
202 just such situations as the one above.</p>
203 <p>Another operator with surprising precedence is exponentiation. It
204 binds more tightly even than unary minus, making <code>-2**2</code> product a
205 negative not a positive four. It is also right-associating, meaning
206 that <code>2**3**2</code> is two raised to the ninth power, not eight squared.</p>
207 <p>Although it has the same precedence as in C, Perl's <code>?:</code> operator
208 produces an lvalue. This assigns $x to either $a or $b, depending
209 on the trueness of $maybe:</p>
210 <pre>
211 ($maybe ? $a : $b) = $x;</pre>
213 </p>
214 <h2><a name="how_do_i_declare_create_a_structure">How do I declare/create a structure?</a></h2>
215 <p>In general, you don't ``declare'' a structure. Just use a (probably
216 anonymous) hash reference. See <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a> and <a href="file://C|\msysgit\mingw\html/pod/perldsc.html">the perldsc manpage</a> for details.
217 Here's an example:</p>
218 <pre>
219 $person = {}; # new anonymous hash
220 $person-&gt;{AGE} = 24; # set field AGE to 24
221 $person-&gt;{NAME} = &quot;Nat&quot;; # set field NAME to &quot;Nat&quot;</pre>
222 <p>If you're looking for something a bit more rigorous, try <a href="file://C|\msysgit\mingw\html/pod/perltoot.html">the perltoot manpage</a>.</p>
224 </p>
225 <h2><a name="how_do_i_create_a_module">How do I create a module?</a></h2>
226 <p>(contributed by brian d foy)</p>
227 <p><a href="file://C|\msysgit\mingw\html/pod/perlmod.html">the perlmod manpage</a>, <a href="file://C|\msysgit\mingw\html/pod/perlmodlib.html">the perlmodlib manpage</a>, <a href="file://C|\msysgit\mingw\html/pod/perlmodstyle.html">the perlmodstyle manpage</a> explain modules
228 in all the gory details. <a href="file://C|\msysgit\mingw\html/pod/perlnewmod.html">the perlnewmod manpage</a> gives a brief
229 overview of the process along with a couple of suggestions
230 about style.</p>
231 <p>If you need to include C code or C library interfaces in
232 your module, you'll need h2xs. h2xs will create the module
233 distribution structure and the initial interface files
234 you'll need. <a href="file://C|\msysgit\mingw\html/pod/perlxs.html">the perlxs manpage</a> and <a href="file://C|\msysgit\mingw\html/pod/perlxstut.html">the perlxstut manpage</a> explain the details.</p>
235 <p>If you don't need to use C code, other tools such as
236 ExtUtils::ModuleMaker and Module::Starter, can help you
237 create a skeleton module distribution.</p>
238 <p>You may also want to see Sam Tregar's ``Writing Perl Modules
239 for CPAN'' ( <a href="http://apress.com/book/bookDisplay.html?bID=14">http://apress.com/book/bookDisplay.html?bID=14</a> )
240 which is the best hands-on guide to creating module
241 distributions.</p>
243 </p>
244 <h2><a name="how_do_i_create_a_class">How do I create a class?</a></h2>
245 <p>See <a href="file://C|\msysgit\mingw\html/pod/perltoot.html">the perltoot manpage</a> for an introduction to classes and objects, as well as
246 <a href="file://C|\msysgit\mingw\html/pod/perlobj.html">the perlobj manpage</a> and <a href="file://C|\msysgit\mingw\html/pod/perlbot.html">the perlbot manpage</a>.</p>
248 </p>
249 <h2><a name="how_can_i_tell_if_a_variable_is_tainted">How can I tell if a variable is tainted?</a></h2>
250 <p>You can use the <code>tainted()</code> function of the Scalar::Util module, available
251 from CPAN (or included with Perl since release 5.8.0).
252 See also <a href="file://C|\msysgit\mingw\html/pod/perlsec.html#laundering_and_detecting_tainted_data">Laundering and Detecting Tainted Data in the perlsec manpage</a>.</p>
254 </p>
255 <h2><a name="what_s_a_closure">What's a closure?</a></h2>
256 <p>Closures are documented in <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a>.</p>
257 <p><em>Closure</em> is a computer science term with a precise but
258 hard-to-explain meaning. Closures are implemented in Perl as anonymous
259 subroutines with lasting references to lexical variables outside their
260 own scopes. These lexicals magically refer to the variables that were
261 around when the subroutine was defined (deep binding).</p>
262 <p>Closures make sense in any programming language where you can have the
263 return value of a function be itself a function, as you can in Perl.
264 Note that some languages provide anonymous functions but are not
265 capable of providing proper closures: the Python language, for
266 example. For more information on closures, check out any textbook on
267 functional programming. Scheme is a language that not only supports
268 but encourages closures.</p>
269 <p>Here's a classic function-generating function:</p>
270 <pre>
271 sub add_function_generator {
272 return sub { shift() + shift() };
273 }</pre>
274 <pre>
275 $add_sub = add_function_generator();
276 $sum = $add_sub-&gt;(4,5); # $sum is 9 now.</pre>
277 <p>The closure works as a <em>function template</em> with some customization
278 slots left out to be filled later. The anonymous subroutine returned
279 by <code>add_function_generator()</code> isn't technically a closure because it
280 refers to no lexicals outside its own scope.</p>
281 <p>Contrast this with the following <code>make_adder()</code> function, in which the
282 returned anonymous function contains a reference to a lexical variable
283 outside the scope of that function itself. Such a reference requires
284 that Perl return a proper closure, thus locking in for all time the
285 value that the lexical had when the function was created.</p>
286 <pre>
287 sub make_adder {
288 my $addpiece = shift;
289 return sub { shift() + $addpiece };
290 }</pre>
291 <pre>
292 $f1 = make_adder(20);
293 $f2 = make_adder(555);</pre>
294 <p>Now <code>&amp;$f1($n)</code> is always 20 plus whatever $n you pass in, whereas
295 <code>&amp;$f2($n)</code> is always 555 plus whatever $n you pass in. The $addpiece
296 in the closure sticks around.</p>
297 <p>Closures are often used for less esoteric purposes. For example, when
298 you want to pass in a bit of code into a function:</p>
299 <pre>
300 my $line;
301 timeout( 30, sub { $line = &lt;STDIN&gt; } );</pre>
302 <p>If the code to execute had been passed in as a string,
303 <code>'$line = &lt;STDIN&gt;'</code>, there would have been no way for the
304 hypothetical <code>timeout()</code> function to access the lexical variable
305 $line back in its caller's scope.</p>
307 </p>
308 <h2><a name="what_is_variable_suicide_and_how_can_i_prevent_it">What is variable suicide and how can I prevent it?</a></h2>
309 <p>This problem was fixed in perl 5.004_05, so preventing it means upgrading
310 your version of perl. ;)</p>
311 <p>Variable suicide is when you (temporarily or permanently) lose the value
312 of a variable. It is caused by scoping through <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my()</code></a> and <code>local()</code>
313 interacting with either closures or aliased <code>foreach()</code> iterator variables
314 and subroutine arguments. It used to be easy to inadvertently lose a
315 variable's value this way, but now it's much harder. Take this code:</p>
316 <pre>
317 my $f = 'foo';
318 sub T {
319 while ($i++ &lt; 3) { my $f = $f; $f .= $i; print $f, &quot;\n&quot; }
322 print &quot;Finally $f\n&quot;;</pre>
323 <p>If you are experiencing variable suicide, that <code>my $f</code> in the subroutine
324 doesn't pick up a fresh copy of the <code>$f</code> whose value is &lt;foo&gt;. The output
325 shows that inside the subroutine the value of <code>$f</code> leaks through when it
326 shouldn't, as in this output:</p>
327 <pre>
328 foobar
329 foobarbar
330 foobarbarbar
331 Finally foo</pre>
332 <p>The $f that has ``bar'' added to it three times should be a new <code>$f</code>
333 <code>my $f</code> should create a new lexical variable each time through the loop.
334 The expected output is:</p>
335 <pre>
336 foobar
337 foobar
338 foobar
339 Finally foo</pre>
341 </p>
342 <h2><a name="how_can_i_pass_return_a__function__filehandle__array__hash__method__regex_">How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?</a></h2>
343 <p>With the exception of regexes, you need to pass references to these
344 objects. See <a href="file://C|\msysgit\mingw\html/pod/perlsub.html#pass_by_reference">Pass by Reference in the perlsub manpage</a> for this particular
345 question, and <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a> for information on references.</p>
346 <p>See ``Passing Regexes'', below, for information on passing regular
347 expressions.</p>
348 <dl>
349 <dt><strong><a name="item_passing_variables_and_functions">Passing Variables and Functions</a></strong>
351 <dd>
352 <p>Regular variables and functions are quite easy to pass: just pass in a
353 reference to an existing or anonymous variable or function:</p>
354 </dd>
355 <dd>
356 <pre>
357 func( \$some_scalar );</pre>
358 </dd>
359 <dd>
360 <pre>
361 func( \@some_array );
362 func( [ 1 .. 10 ] );</pre>
363 </dd>
364 <dd>
365 <pre>
366 func( \%some_hash );
367 func( { this =&gt; 10, that =&gt; 20 } );</pre>
368 </dd>
369 <dd>
370 <pre>
371 func( \&amp;some_func );
372 func( sub { $_[0] ** $_[1] } );</pre>
373 </dd>
374 </li>
375 <dt><strong><a name="item_passing_filehandles">Passing Filehandles</a></strong>
377 <dd>
378 <p>As of Perl 5.6, you can represent filehandles with scalar variables
379 which you treat as any other scalar.</p>
380 </dd>
381 <dd>
382 <pre>
383 open my $fh, $filename or die &quot;Cannot open $filename! $!&quot;;
384 func( $fh );</pre>
385 </dd>
386 <dd>
387 <pre>
388 sub func {
389 my $passed_fh = shift;</pre>
390 </dd>
391 <dd>
392 <pre>
393 my $line = &lt;$fh&gt;;
394 }</pre>
395 </dd>
396 <dd>
397 <p>Before Perl 5.6, you had to use the <code>*FH</code> or <code>\*FH</code> notations.
398 These are ``typeglobs''--see <a href="file://C|\msysgit\mingw\html/pod/perldata.html#typeglobs_and_filehandles">Typeglobs and Filehandles in the perldata manpage</a>
399 and especially <a href="file://C|\msysgit\mingw\html/pod/perlsub.html#pass_by_reference">Pass by Reference in the perlsub manpage</a> for more information.</p>
400 </dd>
401 </li>
402 <dt><strong><a name="item_passing_regexes">Passing Regexes</a></strong>
404 <dd>
405 <p>To pass regexes around, you'll need to be using a release of Perl
406 sufficiently recent as to support the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_qr_"><code>qr//</code></a> construct, pass around
407 strings and use an exception-trapping eval, or else be very, very clever.</p>
408 </dd>
409 <dd>
410 <p>Here's an example of how to pass in a string to be regex compared
411 using <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_qr_"><code>qr//</code></a>:</p>
412 </dd>
413 <dd>
414 <pre>
415 sub compare($$) {
416 my ($val1, $regex) = @_;
417 my $retval = $val1 =~ /$regex/;
418 return $retval;
420 $match = compare(&quot;old McDonald&quot;, qr/d.*D/i);</pre>
421 </dd>
422 <dd>
423 <p>Notice how <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_qr_"><code>qr//</code></a> allows flags at the end. That pattern was compiled
424 at compile time, although it was executed later. The nifty <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_qr_"><code>qr//</code></a>
425 notation wasn't introduced until the 5.005 release. Before that, you
426 had to approach this problem much less intuitively. For example, here
427 it is again if you don't have <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_qr_"><code>qr//</code></a>:</p>
428 </dd>
429 <dd>
430 <pre>
431 sub compare($$) {
432 my ($val1, $regex) = @_;
433 my $retval = eval { $val1 =~ /$regex/ };
434 die if $@;
435 return $retval;
436 }</pre>
437 </dd>
438 <dd>
439 <pre>
440 $match = compare(&quot;old McDonald&quot;, q/($?i)d.*D/);</pre>
441 </dd>
442 <dd>
443 <p>Make sure you never say something like this:</p>
444 </dd>
445 <dd>
446 <pre>
447 return eval &quot;\$val =~ /$regex/&quot;; # WRONG</pre>
448 </dd>
449 <dd>
450 <p>or someone can sneak shell escapes into the regex due to the double
451 interpolation of the eval and the double-quoted string. For example:</p>
452 </dd>
453 <dd>
454 <pre>
455 $pattern_of_evil = 'danger ${ system(&quot;rm -rf * &amp;&quot;) } danger';</pre>
456 </dd>
457 <dd>
458 <pre>
459 eval &quot;\$string =~ /$pattern_of_evil/&quot;;</pre>
460 </dd>
461 <dd>
462 <p>Those preferring to be very, very clever might see the O'Reilly book,
463 <em>Mastering Regular Expressions</em>, by Jeffrey Friedl. Page 273's
464 <code>Build_MatchMany_Function()</code> is particularly interesting. A complete
465 citation of this book is given in <a href="file://C|\msysgit\mingw\html/pod/perlfaq2.html">the perlfaq2 manpage</a>.</p>
466 </dd>
467 </li>
468 <dt><strong><a name="item_passing_methods">Passing Methods</a></strong>
470 <dd>
471 <p>To pass an object method into a subroutine, you can do this:</p>
472 </dd>
473 <dd>
474 <pre>
475 call_a_lot(10, $some_obj, &quot;methname&quot;)
476 sub call_a_lot {
477 my ($count, $widget, $trick) = @_;
478 for (my $i = 0; $i &lt; $count; $i++) {
479 $widget-&gt;$trick();
481 }</pre>
482 </dd>
483 <dd>
484 <p>Or, you can use a closure to bundle up the object, its
485 method call, and arguments:</p>
486 </dd>
487 <dd>
488 <pre>
489 my $whatnot = sub { $some_obj-&gt;obfuscate(@args) };
490 func($whatnot);
491 sub func {
492 my $code = shift;
493 &amp;$code();
494 }</pre>
495 </dd>
496 <dd>
497 <p>You could also investigate the <code>can()</code> method in the UNIVERSAL class
498 (part of the standard perl distribution).</p>
499 </dd>
500 </li>
501 </dl>
503 </p>
504 <h2><a name="how_do_i_create_a_static_variable">How do I create a static variable?</a></h2>
505 <p>(contributed by brian d foy)</p>
506 <p>Perl doesn't have ``static'' variables, which can only be accessed from
507 the function in which they are declared. You can get the same effect
508 with lexical variables, though.</p>
509 <p>You can fake a static variable by using a lexical variable which goes
510 out of scope. In this example, you define the subroutine <code>counter</code>, and
511 it uses the lexical variable <code>$count</code>. Since you wrap this in a BEGIN
512 block, <code>$count</code> is defined at compile-time, but also goes out of
513 scope at the end of the BEGIN block. The BEGIN block also ensures that
514 the subroutine and the value it uses is defined at compile-time so the
515 subroutine is ready to use just like any other subroutine, and you can
516 put this code in the same place as other subroutines in the program
517 text (i.e. at the end of the code, typically). The subroutine
518 <code>counter</code> still has a reference to the data, and is the only way you
519 can access the value (and each time you do, you increment the value).
520 The data in chunk of memory defined by <code>$count</code> is private to
521 <code>counter</code>.</p>
522 <pre>
523 BEGIN {
524 my $count = 1;
525 sub counter { $count++ }
526 }</pre>
527 <pre>
528 my $start = count();</pre>
529 <pre>
530 .... # code that calls count();</pre>
531 <pre>
532 my $end = count();</pre>
533 <p>In the previous example, you created a function-private variable
534 because only one function remembered its reference. You could define
535 multiple functions while the variable is in scope, and each function
536 can share the ``private'' variable. It's not really ``static'' because you
537 can access it outside the function while the lexical variable is in
538 scope, and even create references to it. In this example,
539 <code>increment_count</code> and <code>return_count</code> share the variable. One
540 function adds to the value and the other simply returns the value.
541 They can both access <code>$count</code>, and since it has gone out of scope,
542 there is no other way to access it.</p>
543 <pre>
544 BEGIN {
545 my $count = 1;
546 sub increment_count { $count++ }
547 sub return_count { $count }
548 }</pre>
549 <p>To declare a file-private variable, you still use a lexical variable.
550 A file is also a scope, so a lexical variable defined in the file
551 cannot be seen from any other file.</p>
552 <p>See <a href="file://C|\msysgit\mingw\html/pod/perlsub.html#persistent_private_variables">Persistent Private Variables in the perlsub manpage</a> for more information.
553 The discussion of closures in <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a> may help you even though we
554 did not use anonymous subroutines in this answer. See
555 <a href="file://C|\msysgit\mingw\html/pod/perlsub.html#persistent_private_variables">Persistent Private Variables in the perlsub manpage</a> for details.</p>
557 </p>
558 <h2><a name="what_s_the_difference_between_dynamic_and_lexical__static__scoping_between_local___and_my__">What's the difference between dynamic and lexical (static) scoping? Between <code>local()</code> and my()?</a></h2>
559 <p><code>local($x)</code> saves away the old value of the global variable <code>$x</code>
560 and assigns a new value for the duration of the subroutine <em>which is
561 visible in other functions called from that subroutine</em>. This is done
562 at run-time, so is called dynamic scoping. <code>local()</code> always affects global
563 variables, also called package variables or dynamic variables.</p>
564 <p><a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my($x)</code></a> creates a new variable that is only visible in the current
565 subroutine. This is done at compile-time, so it is called lexical or
566 static scoping. <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my()</code></a> always affects private variables, also called
567 lexical variables or (improperly) static(ly scoped) variables.</p>
568 <p>For instance:</p>
569 <pre>
570 sub visible {
571 print &quot;var has value $var\n&quot;;
572 }</pre>
573 <pre>
574 sub dynamic {
575 local $var = 'local'; # new temporary value for the still-global
576 visible(); # variable called $var
577 }</pre>
578 <pre>
579 sub lexical {
580 my $var = 'private'; # new private variable, $var
581 visible(); # (invisible outside of sub scope)
582 }</pre>
583 <pre>
584 $var = 'global';</pre>
585 <pre>
586 visible(); # prints global
587 dynamic(); # prints local
588 lexical(); # prints global</pre>
589 <p>Notice how at no point does the value ``private'' get printed. That's
590 because $var only has that value within the block of the <code>lexical()</code>
591 function, and it is hidden from called subroutine.</p>
592 <p>In summary, <code>local()</code> doesn't make what you think of as private, local
593 variables. It gives a global variable a temporary value. <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my()</code></a> is
594 what you're looking for if you want private variables.</p>
595 <p>See <a href="file://C|\msysgit\mingw\html/pod/perlsub.html#private_variables_via_my__">Private Variables via my() in the perlsub manpage</a> and
596 <a href="file://C|\msysgit\mingw\html/pod/perlsub.html#temporary_values_via_local__">Temporary Values via local() in the perlsub manpage</a> for excruciating details.</p>
598 </p>
599 <h2><a name="how_can_i_access_a_dynamic_variable_while_a_similarly_named_lexical_is_in_scope">How can I access a dynamic variable while a similarly named lexical is in scope?</a></h2>
600 <p>If you know your package, you can just mention it explicitly, as in
601 $Some_Pack::var. Note that the notation $::var is <strong>not</strong> the dynamic $var
602 in the current package, but rather the one in the ``main'' package, as
603 though you had written $main::var.</p>
604 <pre>
605 use vars '$var';
606 local $var = &quot;global&quot;;
607 my $var = &quot;lexical&quot;;</pre>
608 <pre>
609 print &quot;lexical is $var\n&quot;;
610 print &quot;global is $main::var\n&quot;;</pre>
611 <p>Alternatively you can use the compiler directive <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_our"><code>our()</code></a> to bring a
612 dynamic variable into the current lexical scope.</p>
613 <pre>
614 require 5.006; # our() did not exist before 5.6
615 use vars '$var';</pre>
616 <pre>
617 local $var = &quot;global&quot;;
618 my $var = &quot;lexical&quot;;</pre>
619 <pre>
620 print &quot;lexical is $var\n&quot;;</pre>
621 <pre>
623 our $var;
624 print &quot;global is $var\n&quot;;
625 }</pre>
627 </p>
628 <h2><a name="what_s_the_difference_between_deep_and_shallow_binding">What's the difference between deep and shallow binding?</a></h2>
629 <p>In deep binding, lexical variables mentioned in anonymous subroutines
630 are the same ones that were in scope when the subroutine was created.
631 In shallow binding, they are whichever variables with the same names
632 happen to be in scope when the subroutine is called. Perl always uses
633 deep binding of lexical variables (i.e., those created with my()).
634 However, dynamic variables (aka global, local, or package variables)
635 are effectively shallowly bound. Consider this just one more reason
636 not to use them. See the answer to <a href="#what_s_a_closure">What's a closure?</a>.</p>
638 </p>
639 <h2><a name="why_doesn_t_my__foo_____file___work_right">Why doesn't ``my($foo) = &lt;FILE&gt;;'' work right?</a></h2>
640 <p><a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my()</code></a> and <code>local()</code> give list context to the right hand side
641 of <code>=</code>. The &lt;FH&gt; read operation, like so many of Perl's
642 functions and operators, can tell which context it was called in and
643 behaves appropriately. In general, the <code>scalar()</code> function can help.
644 This function does nothing to the data itself (contrary to popular myth)
645 but rather tells its argument to behave in whatever its scalar fashion is.
646 If that function doesn't have a defined scalar behavior, this of course
647 doesn't help you (such as with sort()).</p>
648 <p>To enforce scalar context in this particular case, however, you need
649 merely omit the parentheses:</p>
650 <pre>
651 local($foo) = &lt;FILE&gt;; # WRONG
652 local($foo) = scalar(&lt;FILE&gt;); # ok
653 local $foo = &lt;FILE&gt;; # right</pre>
654 <p>You should probably be using lexical variables anyway, although the
655 issue is the same here:</p>
656 <pre>
657 my($foo) = &lt;FILE&gt;; # WRONG
658 my $foo = &lt;FILE&gt;; # right</pre>
660 </p>
661 <h2><a name="how_do_i_redefine_a_builtin_function__operator__or_method">How do I redefine a builtin function, operator, or method?</a></h2>
662 <p>Why do you want to do that? :-)</p>
663 <p>If you want to override a predefined function, such as open(),
664 then you'll have to import the new definition from a different
665 module. See <a href="file://C|\msysgit\mingw\html/pod/perlsub.html#overriding_builtin_functions">Overriding Built-in Functions in the perlsub manpage</a>. There's
666 also an example in <a href="file://C|\msysgit\mingw\html/pod/perltoot.html#class__template">Class::Template in the perltoot manpage</a>.</p>
667 <p>If you want to overload a Perl operator, such as <code>+</code> or <code>**</code>,
668 then you'll want to use the <code>use overload</code> pragma, documented
669 in <a href="file://C|\msysgit\mingw\html/lib/overload.html">the overload manpage</a>.</p>
670 <p>If you're talking about obscuring method calls in parent classes,
671 see <a href="file://C|\msysgit\mingw\html/pod/perltoot.html#overridden_methods">Overridden Methods in the perltoot manpage</a>.</p>
673 </p>
674 <h2><a name="what_s_the_difference_between_calling_a_function_as__foo_and_foo__">What's the difference between calling a function as &amp;foo and foo()?</a></h2>
675 <p>When you call a function as <code>&amp;foo</code>, you allow that function access to
676 your current @_ values, and you bypass prototypes.
677 The function doesn't get an empty @_--it gets yours! While not
678 strictly speaking a bug (it's documented that way in <a href="file://C|\msysgit\mingw\html/pod/perlsub.html">the perlsub manpage</a>), it
679 would be hard to consider this a feature in most cases.</p>
680 <p>When you call your function as <code>&amp;foo()</code>, then you <em>do</em> get a new @_,
681 but prototyping is still circumvented.</p>
682 <p>Normally, you want to call a function using <code>foo()</code>. You may only
683 omit the parentheses if the function is already known to the compiler
684 because it already saw the definition (<a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_use"><code>use</code></a> but not <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_require"><code>require</code></a>),
685 or via a forward reference or <code>use subs</code> declaration. Even in this
686 case, you get a clean @_ without any of the old values leaking through
687 where they don't belong.</p>
689 </p>
690 <h2><a name="how_do_i_create_a_switch_or_case_statement">How do I create a switch or case statement?</a></h2>
691 <p>This is explained in more depth in the <a href="file://C|\msysgit\mingw\html/pod/perlsyn.html">the perlsyn manpage</a>. Briefly, there's
692 no official case statement, because of the variety of tests possible
693 in Perl (numeric comparison, string comparison, glob comparison,
694 regex matching, overloaded comparisons, ...).
695 Larry couldn't decide how best to do this, so he left it out, even
696 though it's been on the wish list since perl1.</p>
697 <p>Starting from Perl 5.8 to get switch and case one can use the
698 Switch extension and say:</p>
699 <pre>
700 use Switch;</pre>
701 <p>after which one has switch and case. It is not as fast as it could be
702 because it's not really part of the language (it's done using source
703 filters) but it is available, and it's very flexible.</p>
704 <p>But if one wants to use pure Perl, the general answer is to write a
705 construct like this:</p>
706 <pre>
707 for ($variable_to_test) {
708 if (/pat1/) { } # do something
709 elsif (/pat2/) { } # do something else
710 elsif (/pat3/) { } # do something else
711 else { } # default
712 }</pre>
713 <p>Here's a simple example of a switch based on pattern matching, this
714 time lined up in a way to make it look more like a switch statement.
715 We'll do a multiway conditional based on the type of reference stored
716 in $whatchamacallit:</p>
717 <pre>
718 SWITCH: for (ref $whatchamacallit) {</pre>
719 <pre>
720 /^$/ &amp;&amp; die &quot;not a reference&quot;;</pre>
721 <pre>
722 /SCALAR/ &amp;&amp; do {
723 print_scalar($$ref);
724 last SWITCH;
725 };</pre>
726 <pre>
727 /ARRAY/ &amp;&amp; do {
728 print_array(@$ref);
729 last SWITCH;
730 };</pre>
731 <pre>
732 /HASH/ &amp;&amp; do {
733 print_hash(%$ref);
734 last SWITCH;
735 };</pre>
736 <pre>
737 /CODE/ &amp;&amp; do {
738 warn &quot;can't print function ref&quot;;
739 last SWITCH;
740 };</pre>
741 <pre>
742 # DEFAULT</pre>
743 <pre>
744 warn &quot;User defined type skipped&quot;;</pre>
745 <pre>
746 }</pre>
747 <p>See <code>perlsyn/&quot;Basic BLOCKs and Switch Statements&quot;</code> for many other
748 examples in this style.</p>
749 <p>Sometimes you should change the positions of the constant and the variable.
750 For example, let's say you wanted to test which of many answers you were
751 given, but in a case-insensitive way that also allows abbreviations.
752 You can use the following technique if the strings all start with
753 different characters or if you want to arrange the matches so that
754 one takes precedence over another, as <code>&quot;SEND&quot;</code> has precedence over
755 <code>&quot;STOP&quot;</code> here:</p>
756 <pre>
757 chomp($answer = &lt;&gt;);
758 if (&quot;SEND&quot; =~ /^\Q$answer/i) { print &quot;Action is send\n&quot; }
759 elsif (&quot;STOP&quot; =~ /^\Q$answer/i) { print &quot;Action is stop\n&quot; }
760 elsif (&quot;ABORT&quot; =~ /^\Q$answer/i) { print &quot;Action is abort\n&quot; }
761 elsif (&quot;LIST&quot; =~ /^\Q$answer/i) { print &quot;Action is list\n&quot; }
762 elsif (&quot;EDIT&quot; =~ /^\Q$answer/i) { print &quot;Action is edit\n&quot; }</pre>
763 <p>A totally different approach is to create a hash of function references.</p>
764 <pre>
765 my %commands = (
766 &quot;happy&quot; =&gt; \&amp;joy,
767 &quot;sad&quot;, =&gt; \&amp;sullen,
768 &quot;done&quot; =&gt; sub { die &quot;See ya!&quot; },
769 &quot;mad&quot; =&gt; \&amp;angry,
770 );</pre>
771 <pre>
772 print &quot;How are you? &quot;;
773 chomp($string = &lt;STDIN&gt;);
774 if ($commands{$string}) {
775 $commands{$string}-&gt;();
776 } else {
777 print &quot;No such command: $string\n&quot;;
778 }</pre>
780 </p>
781 <h2><a name="how_can_i_catch_accesses_to_undefined_variables__functions__or_methods">How can I catch accesses to undefined variables, functions, or methods?</a></h2>
782 <p>The AUTOLOAD method, discussed in <a href="file://C|\msysgit\mingw\html/pod/perlsub.html#autoloading">Autoloading in the perlsub manpage</a> and
783 <a href="file://C|\msysgit\mingw\html/pod/perltoot.html#autoload__proxy_methods">AUTOLOAD: Proxy Methods in the perltoot manpage</a>, lets you capture calls to
784 undefined functions and methods.</p>
785 <p>When it comes to undefined variables that would trigger a warning
786 under <code>use warnings</code>, you can promote the warning to an error.</p>
787 <pre>
788 use warnings FATAL =&gt; qw(uninitialized);</pre>
790 </p>
791 <h2><a name="why_can_t_a_method_included_in_this_same_file_be_found">Why can't a method included in this same file be found?</a></h2>
792 <p>Some possible reasons: your inheritance is getting confused, you've
793 misspelled the method name, or the object is of the wrong type. Check
794 out <a href="file://C|\msysgit\mingw\html/pod/perltoot.html">the perltoot manpage</a> for details about any of the above cases. You may
795 also use <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_ref"><code>print ref($object)</code></a> to find out the class <code>$object</code> was
796 blessed into.</p>
797 <p>Another possible reason for problems is because you've used the
798 indirect object syntax (eg, <code>find Guru &quot;Samy&quot;</code>) on a class name
799 before Perl has seen that such a package exists. It's wisest to make
800 sure your packages are all defined before you start using them, which
801 will be taken care of if you use the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_use"><code>use</code></a> statement instead of
802 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_require"><code>require</code></a>. If not, make sure to use arrow notation (eg.,
803 <code>Guru-&gt;find(&quot;Samy&quot;)</code>) instead. Object notation is explained in
804 <a href="file://C|\msysgit\mingw\html/pod/perlobj.html">the perlobj manpage</a>.</p>
805 <p>Make sure to read about creating modules in <a href="file://C|\msysgit\mingw\html/pod/perlmod.html">the perlmod manpage</a> and
806 the perils of indirect objects in <a href="file://C|\msysgit\mingw\html/pod/perlobj.html#method_invocation">Method Invocation in the perlobj manpage</a>.</p>
808 </p>
809 <h2><a name="how_can_i_find_out_my_current_package">How can I find out my current package?</a></h2>
810 <p>If you're just a random program, you can do this to find
811 out what the currently compiled package is:</p>
812 <pre>
813 my $packname = __PACKAGE__;</pre>
814 <p>But, if you're a method and you want to print an error message
815 that includes the kind of object you were called on (which is
816 not necessarily the same as the one in which you were compiled):</p>
817 <pre>
818 sub amethod {
819 my $self = shift;
820 my $class = ref($self) || $self;
821 warn &quot;called me from a $class object&quot;;
822 }</pre>
824 </p>
825 <h2><a name="how_can_i_comment_out_a_large_block_of_perl_code">How can I comment out a large block of perl code?</a></h2>
826 <p>You can use embedded POD to discard it. Enclose the blocks you want
827 to comment out in POD markers. The &lt;=begin&gt; directive marks a section
828 for a specific formatter. Use the <code>comment</code> format, which no formatter
829 should claim to understand (by policy). Mark the end of the block
830 with &lt;=end&gt;.</p>
831 <pre>
832 # program is here</pre>
833 <pre>
834 =begin comment</pre>
835 <pre>
836 all of this stuff</pre>
837 <pre>
838 here will be ignored
839 by everyone</pre>
840 <pre>
841 =end comment</pre>
842 <pre>
843 =cut</pre>
844 <pre>
845 # program continues</pre>
846 <p>The pod directives cannot go just anywhere. You must put a
847 pod directive where the parser is expecting a new statement,
848 not just in the middle of an expression or some other
849 arbitrary grammar production.</p>
850 <p>See <a href="file://C|\msysgit\mingw\html/pod/perlpod.html">the perlpod manpage</a> for more details.</p>
852 </p>
853 <h2><a name="how_do_i_clear_a_package">How do I clear a package?</a></h2>
854 <p>Use this code, provided by Mark-Jason Dominus:</p>
855 <pre>
856 sub scrub_package {
857 no strict 'refs';
858 my $pack = shift;
859 die &quot;Shouldn't delete main package&quot;
860 if $pack eq &quot;&quot; || $pack eq &quot;main&quot;;
861 my $stash = *{$pack . '::'}{HASH};
862 my $name;
863 foreach $name (keys %$stash) {
864 my $fullname = $pack . '::' . $name;
865 # Get rid of everything with that name.
866 undef $$fullname;
867 undef @$fullname;
868 undef %$fullname;
869 undef &amp;$fullname;
870 undef *$fullname;
872 }</pre>
873 <p>Or, if you're using a recent release of Perl, you can
874 just use the Symbol::delete_package() function instead.</p>
876 </p>
877 <h2><a name="how_can_i_use_a_variable_as_a_variable_name">How can I use a variable as a variable name?</a></h2>
878 <p>Beginners often think they want to have a variable contain the name
879 of a variable.</p>
880 <pre>
881 $fred = 23;
882 $varname = &quot;fred&quot;;
883 ++$$varname; # $fred now 24</pre>
884 <p>This works <em>sometimes</em>, but it is a very bad idea for two reasons.</p>
885 <p>The first reason is that this technique <em>only works on global
886 variables</em>. That means that if $fred is a lexical variable created
887 with <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my()</code></a> in the above example, the code wouldn't work at all: you'd
888 accidentally access the global and skip right over the private lexical
889 altogether. Global variables are bad because they can easily collide
890 accidentally and in general make for non-scalable and confusing code.</p>
891 <p>Symbolic references are forbidden under the <code>use strict</code> pragma.
892 They are not true references and consequently are not reference counted
893 or garbage collected.</p>
894 <p>The other reason why using a variable to hold the name of another
895 variable is a bad idea is that the question often stems from a lack of
896 understanding of Perl data structures, particularly hashes. By using
897 symbolic references, you are just using the package's symbol-table hash
898 (like <code>%main::</code>) instead of a user-defined hash. The solution is to
899 use your own hash or a real reference instead.</p>
900 <pre>
901 $USER_VARS{&quot;fred&quot;} = 23;
902 $varname = &quot;fred&quot;;
903 $USER_VARS{$varname}++; # not $$varname++</pre>
904 <p>There we're using the %USER_VARS hash instead of symbolic references.
905 Sometimes this comes up in reading strings from the user with variable
906 references and wanting to expand them to the values of your perl
907 program's variables. This is also a bad idea because it conflates the
908 program-addressable namespace and the user-addressable one. Instead of
909 reading a string and expanding it to the actual contents of your program's
910 own variables:</p>
911 <pre>
912 $str = 'this has a $fred and $barney in it';
913 $str =~ s/(\$\w+)/$1/eeg; # need double eval</pre>
914 <p>it would be better to keep a hash around like %USER_VARS and have
915 variable references actually refer to entries in that hash:</p>
916 <pre>
917 $str =~ s/\$(\w+)/$USER_VARS{$1}/g; # no /e here at all</pre>
918 <p>That's faster, cleaner, and safer than the previous approach. Of course,
919 you don't need to use a dollar sign. You could use your own scheme to
920 make it less confusing, like bracketed percent symbols, etc.</p>
921 <pre>
922 $str = 'this has a %fred% and %barney% in it';
923 $str =~ s/%(\w+)%/$USER_VARS{$1}/g; # no /e here at all</pre>
924 <p>Another reason that folks sometimes think they want a variable to
925 contain the name of a variable is because they don't know how to build
926 proper data structures using hashes. For example, let's say they
927 wanted two hashes in their program: %fred and %barney, and that they
928 wanted to use another scalar variable to refer to those by name.</p>
929 <pre>
930 $name = &quot;fred&quot;;
931 $$name{WIFE} = &quot;wilma&quot;; # set %fred</pre>
932 <pre>
933 $name = &quot;barney&quot;;
934 $$name{WIFE} = &quot;betty&quot;; # set %barney</pre>
935 <p>This is still a symbolic reference, and is still saddled with the
936 problems enumerated above. It would be far better to write:</p>
937 <pre>
938 $folks{&quot;fred&quot;}{WIFE} = &quot;wilma&quot;;
939 $folks{&quot;barney&quot;}{WIFE} = &quot;betty&quot;;</pre>
940 <p>And just use a multilevel hash to start with.</p>
941 <p>The only times that you absolutely <em>must</em> use symbolic references are
942 when you really must refer to the symbol table. This may be because it's
943 something that can't take a real reference to, such as a format name.
944 Doing so may also be important for method calls, since these always go
945 through the symbol table for resolution.</p>
946 <p>In those cases, you would turn off <code>strict 'refs'</code> temporarily so you
947 can play around with the symbol table. For example:</p>
948 <pre>
949 @colors = qw(red blue green yellow orange purple violet);
950 for my $name (@colors) {
951 no strict 'refs'; # renege for the block
952 *$name = sub { &quot;&lt;FONT COLOR='$name'&gt;@_&lt;/FONT&gt;&quot; };
953 }</pre>
954 <p>All those functions (red(), blue(), green(), etc.) appear to be separate,
955 but the real code in the closure actually was compiled only once.</p>
956 <p>So, sometimes you might want to use symbolic references to directly
957 manipulate the symbol table. This doesn't matter for formats, handles, and
958 subroutines, because they are always global--you can't use <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my()</code></a> on them.
959 For scalars, arrays, and hashes, though--and usually for subroutines--
960 you probably only want to use hard references.</p>
962 </p>
963 <h2><a name="what_does_bad_interpreter_mean">What does ``bad interpreter'' mean?</a></h2>
964 <p>(contributed by brian d foy)</p>
965 <p>The ``bad interpreter'' message comes from the shell, not perl. The
966 actual message may vary depending on your platform, shell, and locale
967 settings.</p>
968 <p>If you see ``bad interpreter - no such file or directory'', the first
969 line in your perl script (the ``shebang'' line) does not contain the
970 right path to perl (or any other program capable of running scripts).
971 Sometimes this happens when you move the script from one machine to
972 another and each machine has a different path to perl---/usr/bin/perl
973 versus /usr/local/bin/perl for instance. It may also indicate
974 that the source machine has CRLF line terminators and the
975 destination machine has LF only: the shell tries to find
976 /usr/bin/perl&lt;CR&gt;, but can't.</p>
977 <p>If you see ``bad interpreter: Permission denied'', you need to make your
978 script executable.</p>
979 <p>In either case, you should still be able to run the scripts with perl
980 explicitly:</p>
981 <pre>
982 % perl script.pl</pre>
983 <p>If you get a message like ``perl: command not found'', perl is not in
984 your PATH, which might also mean that the location of perl is not
985 where you expect it so you need to adjust your shebang line.</p>
987 </p>
988 <hr />
989 <h1><a name="author_and_copyright">AUTHOR AND COPYRIGHT</a></h1>
990 <p>Copyright (c) 1997-2006 Tom Christiansen, Nathan Torkington, and
991 other authors as noted. All rights reserved.</p>
992 <p>This documentation is free; you can redistribute it and/or modify it
993 under the same terms as Perl itself.</p>
994 <p>Irrespective of its distribution, all code examples in this file
995 are hereby placed into the public domain. You are permitted and
996 encouraged to use this code in your own programs for fun
997 or for profit as you see fit. A simple comment in the code giving
998 credit would be courteous but is not required.</p>
999 <table border="0" width="100%" cellspacing="0" cellpadding="3">
1000 <tr><td class="block" style="background-color: #cccccc" valign="middle">
1001 <big><strong><span class="block">&nbsp;perlfaq7 - General Perl Language Issues</span></strong></big>
1002 </td></tr>
1003 </table>
1005 </body>
1007 </html>