<STRONG><P CLASS=block> perlfaq7 - Perl Language Issues</P></STRONG>
</TD></TR>
</TABLE>
<A NAME="__index__"></A>
<!-- INDEX BEGIN -->
<UL>
<LI><A HREF="#name">NAME</A></LI>
<LI><A HREF="#description">DESCRIPTION</A></LI>
<UL>
<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>
<LI><A HREF="#what are all these $@%&* punctuation signs, and how do i know when to use them">What are all these $@%&* punctuation signs, and how do I know when to use them?</A></LI>
<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>
<LI><A HREF="#how do i skip some return values">How do I skip some return values?</A></LI>
<LI><A HREF="#how do i temporarily block warnings">How do I temporarily block warnings?</A></LI>
<LI><A HREF="#what's an extension">What's an extension?</A></LI>
<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>
<LI><A HREF="#how do i declare/create a structure">How do I declare/create a structure?</A></LI>
<LI><A HREF="#how do i create a module">How do I create a module?</A></LI>
<LI><A HREF="#how do i create a class">How do I create a class?</A></LI>
<LI><A HREF="#how can i tell if a variable is tainted">How can I tell if a variable is tainted?</A></LI>
<LI><A HREF="#what's a closure">What's a closure?</A></LI>
<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>
<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>
<LI><A HREF="#how do i create a static variable">How do I create a static variable?</A></LI>
<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 <A HREF="../../lib/Pod/perlfunc.html#item_local"><CODE>local()</CODE></A> and my()?</A></LI>
<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>
<LI><A HREF="#what's the difference between deep and shallow binding">What's the difference between deep and shallow binding?</A></LI>
<LI><A HREF="#why doesn't my($foo) = <file>; work right">Why doesn't ``my($foo) = <FILE>;'' work right?</A></LI>
<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>
<LI><A HREF="#what's the difference between calling a function as &foo and foo()">What's the difference between calling a function as &foo and foo()?</A></LI>
<LI><A HREF="#how do i create a switch or case statement">How do I create a switch or case statement?</A></LI>
<LI><A HREF="#how can i catch accesses to undefined variables/functions/methods">How can I catch accesses to undefined variables/functions/methods?</A></LI>
<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>
<LI><A HREF="#how can i find out my current package">How can I find out my current package?</A></LI>
<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>
<LI><A HREF="#how do i clear a package">How do I clear a package?</A></LI>
<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>
</UL>
<LI><A HREF="#author and copyright">AUTHOR AND COPYRIGHT</A></LI>
<P>This section deals with general Perl language issues that don't
clearly fit into any of the other sections.</P>
<P>
<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>
<P>There is no BNF, but you can paw your way through the yacc grammar in
perly.y in the source distribution if you're particularly brave. The
grammar relies on very smart tokenizing code, so be prepared to
venture into toke.c as well.</P>
<P>In the words of Chaim Frenkel: ``Perl's grammar can not be reduced to BNF.
The work of parsing perl is distributed between yacc, the lexer, smoke
and mirrors.''</P>
<P>
<H2><A NAME="what are all these $@%&* punctuation signs, and how do i know when to use them">What are all these $@%&* punctuation signs, and how do I know when to use them?</A></H2>
<P>They are type specifiers, as detailed in <A HREF="../../lib/Pod/perldata.html">the perldata manpage</A>:</P>
<PRE>
$ for scalar values (number, string or reference)
@ for arrays
% for hashes (associative arrays)
& for subroutines (aka functions, procedures, methods)
* for all types of that symbol name. In version 4 you used them like
pointers, but in modern perls you can just use references.</PRE>
<P>A couple of others that you're likely to encounter that aren't
really type specifiers are:</P>
<PRE>
<> are used for inputting a record from a filehandle.
\ takes a reference to something.</PRE>
<P>Note that <FILE> is <EM>neither</EM> the type specifier for files
nor the name of the handle. It is the <CODE><></CODE> operator applied
to the handle FILE. It reads one line (well, record - see
<A HREF="../../lib/Pod/perlvar.html#$/">$/ in the perlvar manpage</A>) from the handle FILE in scalar context, or <EM>all</EM> lines
in list context. When performing open, close, or any other operation
besides <CODE><></CODE> on files, or even talking about the handle, do
<EM>not</EM> use the brackets. These are correct: <A HREF="../../lib/Pod/perlfunc.html#item_eof"><CODE>eof(FH)</CODE></A>, <A HREF="../../lib/Pod/perlfunc.html#item_seek"><CODE>seek(FH, 0,
2)</CODE></A> and ``copying from STDIN to FILE''.</P>
<P>
<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>
<P>Normally, a bareword doesn't need to be quoted, but in most cases
probably should be (and must be under <CODE>use strict</CODE>). But a hash key
consisting of a simple word (that isn't the name of a defined
subroutine) and the left-hand operand to the <CODE>=></CODE> operator both
count as though they were quoted:</P>
<PRE>
This is like this
------------ ---------------
$foo{line} $foo{"line"}
bar => stuff "bar" => stuff</PRE>
<P>The final semicolon in a block is optional, as is the final comma in a
list. Good style (see <A HREF="../../lib/Pod/perlstyle.html">the perlstyle manpage</A>) says to put them in except for
one-liners:</P>
<PRE>
if ($whoops) { exit 1 }
@nums = (1, 2, 3);</PRE>
<PRE>
if ($whoops) {
exit 1;
}
@lines = (
"There Beren came from mountains cold",
"And lost he wandered under leaves",
);</PRE>
<P>
<H2><A NAME="how do i skip some return values">How do I skip some return values?</A></H2>
<P>One way is to treat the return values as a list and index into it:</P>
<PRE>
$dir = (getpwnam($user))[7];</PRE>
<P>Another way is to use undef as an element on the left-hand-side:</P>
<H2><A NAME="how do i temporarily block warnings">How do I temporarily block warnings?</A></H2>
<P>If you are running Perl 5.6.0 or better, the <CODE>use warnings</CODE> pragma
allows fine control of what warning are produced.
See <A HREF="../../lib/Pod/perllexwarn.html">the perllexwarn manpage</A> for more details.</P>
<PRE>
{
no warnings; # temporarily turn off warnings
$a = $b + $c; # I know these might be undef
}</PRE>
<P>If you have an older version of Perl, the <CODE>$^W</CODE> variable (documented
in <A HREF="../../lib/Pod/perlvar.html">the perlvar manpage</A>) controls runtime warnings for a block:</P>
<PRE>
{
local $^W = 0; # temporarily turn off warnings
$a = $b + $c; # I know these might be undef
}</PRE>
<P>Note that like all the punctuation variables, you cannot currently
use <A HREF="../../lib/Pod/perlfunc.html#item_my"><CODE>my()</CODE></A> on <CODE>$^W</CODE>, only local().</P>
<P>
<H2><A NAME="what's an extension">What's an extension?</A></H2>
<P>A way of calling compiled C code from Perl. Reading <A HREF="../../lib/Pod/perlxstut.html">the perlxstut manpage</A>
is a good place to learn more about extensions.</P>
<P>
<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>
<P>Actually, they don't. All C operators that Perl copies have the same
precedence in Perl as they do in C. The problem is with operators that C
doesn't have, especially functions that give a list context to everything
on their right, eg print, chmod, exec, and so on. Such functions are
called ``list operators'' and appear as such in the precedence table in
<P>To avoid this problem, either put in extra parentheses or use the
super low precedence <CODE>or</CODE> operator:</P>
<PRE>
(unlink $file) || die "snafu";
unlink $file or die "snafu";</PRE>
<P>The ``English'' operators (<CODE>and</CODE>, <CODE>or</CODE>, <CODE>xor</CODE>, and <CODE>not</CODE>)
deliberately have precedence lower than that of list operators for
just such situations as the one above.</P>
<P>Another operator with surprising precedence is exponentiation. It
binds more tightly even than unary minus, making <CODE>-2**2</CODE> product a
negative not a positive four. It is also right-associating, meaning
that <CODE>2**3**2</CODE> is two raised to the ninth power, not eight squared.</P>
<P>Although it has the same precedence as in C, Perl's <CODE>?:</CODE> operator
produces an lvalue. This assigns $x to either $a or $b, depending
on the trueness of $maybe:</P>
<PRE>
($maybe ? $a : $b) = $x;</PRE>
<P>
<H2><A NAME="how do i declare/create a structure">How do I declare/create a structure?</A></H2>
<P>In general, you don't ``declare'' a structure. Just use a (probably
anonymous) hash reference. See <A HREF="../../lib/Pod/perlref.html">the perlref manpage</A> and <A HREF="../../lib/Pod/perldsc.html">the perldsc manpage</A> for details.
Here's an example:</P>
<PRE>
$person = {}; # new anonymous hash
$person->{AGE} = 24; # set field AGE to 24
$person->{NAME} = "Nat"; # set field NAME to "Nat"</PRE>
<P>If you're looking for something a bit more rigorous, try <A HREF="../../lib/Pod/perltoot.html">the perltoot manpage</A>.</P>
<P>
<H2><A NAME="how do i create a module">How do I create a module?</A></H2>
<P>A module is a package that lives in a file of the same name. For
example, the Hello::There module would live in Hello/There.pm. For
details, read <A HREF="../../lib/Pod/perlmod.html">the perlmod manpage</A>. You'll also find <A HREF="../../lib/Exporter.html">the Exporter manpage</A> helpful. If
you're writing a C or mixed-language module with both C and Perl, then
you should study <A HREF="../../lib/Pod/perlxstut.html">the perlxstut manpage</A>.</P>
<P>Here's a convenient template you might wish you use when starting your
own module. Make sure to change the names appropriately.</P>
# then the others (which are still accessible as $Some::Module::stuff)
$stuff = '';
@more = ();</PRE>
<PRE>
# all file-scoped lexicals must be created before
# the functions below that use them.</PRE>
<PRE>
# file-private lexicals go here
my $priv_var = '';
my %secret_hash = ();</PRE>
<PRE>
# here's a file-private function as a closure,
# callable as &$priv_func; it cannot be prototyped.
my $priv_func = sub {
# stuff goes here.
};</PRE>
<PRE>
# make all your functions, whether exported or not;
# remember to put something interesting in the {} stubs
sub func1 {} # no prototype
sub func2() {} # proto'd void
sub func3($$) {} # proto'd to 2 scalars</PRE>
<PRE>
# this one isn't exported, but could be called!
sub func4(\%) {} # proto'd to 1 hash ref</PRE>
<PRE>
END { } # module clean-up code here (global destructor)</PRE>
<PRE>
1; # modules must return true</PRE>
<P>The h2xs program will create stubs for all the important stuff for you:</P>
<PRE>
% h2xs -XA -n My::Module</PRE>
<P>
<H2><A NAME="how do i create a class">How do I create a class?</A></H2>
<P>See <A HREF="../../lib/Pod/perltoot.html">the perltoot manpage</A> for an introduction to classes and objects, as well as
<A HREF="../../lib/Pod/perlobj.html">the perlobj manpage</A> and <A HREF="../../lib/Pod/perlbot.html">the perlbot manpage</A>.</P>
<P>
<H2><A NAME="how can i tell if a variable is tainted">How can I tell if a variable is tainted?</A></H2>
<P>See <A HREF="../../lib/Pod/perlsec.html#laundering and detecting tainted data">Laundering and Detecting Tainted Data in the perlsec manpage</A>. Here's an
example (which doesn't use any system calls, because the <A HREF="../../lib/Pod/perlfunc.html#item_kill"><CODE>kill()</CODE></A>
is given no processes to signal):</P>
<PRE>
sub is_tainted {
return ! eval { join('',@_), kill 0; 1; };
}</PRE>
<P>This is not <CODE>-w</CODE> clean, however. There is no <CODE>-w</CODE> clean way to
detect taintedness - take this as a hint that you should untaint
all possibly-tainted data.</P>
<P>
<H2><A NAME="what's a closure">What's a closure?</A></H2>
<P>Closures are documented in <A HREF="../../lib/Pod/perlref.html">the perlref manpage</A>.</P>
<P><EM>Closure</EM> is a computer science term with a precise but
hard-to-explain meaning. Closures are implemented in Perl as anonymous
subroutines with lasting references to lexical variables outside their
own scopes. These lexicals magically refer to the variables that were
around when the subroutine was defined (deep binding).</P>
<P>Closures make sense in any programming language where you can have the
return value of a function be itself a function, as you can in Perl.
Note that some languages provide anonymous functions but are not
capable of providing proper closures; the Python language, for
example. For more information on closures, check out any textbook on
functional programming. Scheme is a language that not only supports
but encourages closures.</P>
<P>Here's a classic function-generating function:</P>
<PRE>
sub add_function_generator {
return sub { shift + shift };
}</PRE>
<PRE>
$add_sub = add_function_generator();
$sum = $add_sub->(4,5); # $sum is 9 now.</PRE>
<P>The closure works as a <EM>function template</EM> with some customization
slots left out to be filled later. The anonymous subroutine returned
by <CODE>add_function_generator()</CODE> isn't technically a closure because it
refers to no lexicals outside its own scope.</P>
<P>Contrast this with the following <CODE>make_adder()</CODE> function, in which the
returned anonymous function contains a reference to a lexical variable
outside the scope of that function itself. Such a reference requires
that Perl return a proper closure, thus locking in for all time the
value that the lexical had when the function was created.</P>
<PRE>
sub make_adder {
my $addpiece = shift;
return sub { shift + $addpiece };
}</PRE>
<PRE>
$f1 = make_adder(20);
$f2 = make_adder(555);</PRE>
<P>Now <CODE>&$f1($n)</CODE> is always 20 plus whatever $n you pass in, whereas
<CODE>&$f2($n)</CODE> is always 555 plus whatever $n you pass in. The $addpiece
in the closure sticks around.</P>
<P>Closures are often used for less esoteric purposes. For example, when
you want to pass in a bit of code into a function:</P>
<PRE>
my $line;
timeout( 30, sub { $line = <STDIN> } );</PRE>
<P>If the code to execute had been passed in as a string,
<CODE>'$line = <STDIN>'</CODE>, there would have been no way for the
hypothetical <CODE>timeout()</CODE> function to access the lexical variable
$line back in its caller's scope.</P>
<P>
<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>
<P>Variable suicide is when you (temporarily or permanently) lose the
value of a variable. It is caused by scoping through <A HREF="../../lib/Pod/perlfunc.html#item_my"><CODE>my()</CODE></A> and <A HREF="../../lib/Pod/perlfunc.html#item_local"><CODE>local()</CODE></A>
interacting with either closures or aliased <CODE>foreach()</CODE> iterator
variables and subroutine arguments. It used to be easy to
inadvertently lose a variable's value this way, but now it's much
harder. Take this code:</P>
<PRE>
my $f = "foo";
sub T {
while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" }
}
T;
print "Finally $f\n";</PRE>
<P>The $f that has ``bar'' added to it three times should be a new <CODE>$f</CODE>
(<CODE>my $f</CODE> should create a new local variable each time through the loop).
It isn't, however. This was a bug, now fixed in the latest releases
(tested against 5.004_05, 5.005_03, and 5.005_56).</P>
<P>
<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>
<P>With the exception of regexes, you need to pass references to these
objects. See <A HREF="../../lib/Pod/perlsub.html#pass by reference">Pass by Reference in the perlsub manpage</A> for this particular
question, and <A HREF="../../lib/Pod/perlref.html">the perlref manpage</A> for information on references.</P>
<DL>
<DT><STRONG><A NAME="item_Passing_Variables_and_Functions">Passing Variables and Functions</A></STRONG><BR>
<DD>
Regular variables and functions are quite easy: just pass in a
reference to an existing or anonymous variable or function:
To pass an object method into a subroutine, you can do this:
<PRE>
call_a_lot(10, $some_obj, "methname")
sub call_a_lot {
my ($count, $widget, $trick) = @_;
for (my $i = 0; $i < $count; $i++) {
$widget->$trick();
}
}</PRE>
<P>Or you can use a closure to bundle up the object and its method call
and arguments:</P>
<PRE>
my $whatnot = sub { $some_obj->obfuscate(@args) };
func($whatnot);
sub func {
my $code = shift;
&$code();
}</PRE>
<P>You could also investigate the <CODE>can()</CODE> method in the UNIVERSAL class
(part of the standard perl distribution).</P>
<P></P></DL>
<P>
<H2><A NAME="how do i create a static variable">How do I create a static variable?</A></H2>
<P>As with most things in Perl, TMTOWTDI. What is a ``static variable'' in
other languages could be either a function-private variable (visible
only within a single function, retaining its value between calls to
that function), or a file-private variable (visible only to functions
within the file it was declared in) in Perl.</P>
<P>Here's code to implement a function-private variable:</P>
<PRE>
BEGIN {
my $counter = 42;
sub prev_counter { return --$counter }
sub next_counter { return $counter++ }
}</PRE>
<P>Now <CODE>prev_counter()</CODE> and <CODE>next_counter()</CODE> share a private variable $counter
that was initialized at compile time.</P>
<P>To declare a file-private variable, you'll still use a my(), putting
it at the outer scope level at the top of the file. Assume this is in
file Pax.pm:</P>
<PRE>
package Pax;
my $started = scalar(localtime(time()));</PRE>
<PRE>
sub begun { return $started }</PRE>
<P>When <CODE>use Pax</CODE> or <CODE>require Pax</CODE> loads this module, the variable will
be initialized. It won't get garbage-collected the way most variables
going out of scope do, because the <CODE>begun()</CODE> function cares about it,
but no one else can get it. It is not called $Pax::started because
its scope is unrelated to the package. It's scoped to the file. You
could conceivably have several packages in that same file all
accessing the same private variable, but another file with the same
package couldn't get to it.</P>
<P>See <A HREF="../../lib/Pod/perlsub.html#persistent private variables">Persistent Private Variables in the perlsub manpage</A> for details.</P>
<P>
<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 <A HREF="../../lib/Pod/perlfunc.html#item_local"><CODE>local()</CODE></A> and my()?</A></H2>
<P><A HREF="../../lib/Pod/perlfunc.html#item_local"><CODE>local($x)</CODE></A> saves away the old value of the global variable <CODE>$x</CODE>,
and assigns a new value for the duration of the subroutine, <EM>which is
visible in other functions called from that subroutine</EM>. This is done
at run-time, so is called dynamic scoping. <A HREF="../../lib/Pod/perlfunc.html#item_local"><CODE>local()</CODE></A> always affects global
variables, also called package variables or dynamic variables.</P>
<P><A HREF="../../lib/Pod/perlfunc.html#item_my"><CODE>my($x)</CODE></A> creates a new variable that is only visible in the current
subroutine. This is done at compile-time, so is called lexical or
static scoping. <A HREF="../../lib/Pod/perlfunc.html#item_my"><CODE>my()</CODE></A> always affects private variables, also called
lexical variables or (improperly) static(ly scoped) variables.</P>
<P>For instance:</P>
<PRE>
sub visible {
print "var has value $var\n";
}</PRE>
<PRE>
sub dynamic {
local $var = 'local'; # new temporary value for the still-global
visible(); # variable called $var
}</PRE>
<PRE>
sub lexical {
my $var = 'private'; # new private variable, $var
visible(); # (invisible outside of sub scope)
}</PRE>
<PRE>
$var = 'global';</PRE>
<PRE>
visible(); # prints global
dynamic(); # prints local
lexical(); # prints global</PRE>
<P>Notice how at no point does the value ``private'' get printed. That's
because $var only has that value within the block of the <CODE>lexical()</CODE>
function, and it is hidden from called subroutine.</P>
<P>In summary, <A HREF="../../lib/Pod/perlfunc.html#item_local"><CODE>local()</CODE></A> doesn't make what you think of as private, local
variables. It gives a global variable a temporary value. <A HREF="../../lib/Pod/perlfunc.html#item_my"><CODE>my()</CODE></A> is
what you're looking for if you want private variables.</P>
<P>See <A HREF="../../lib/Pod/perlsub.html#private variables via my()">Private Variables via my() in the perlsub manpage</A> and <A HREF="../../lib/Pod/perlsub.html#temporary values via local()">Temporary Values via local() in the perlsub manpage</A> for excruciating details.</P>
<P>
<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>
<P>You can do this via symbolic references, provided you haven't set
<CODE>use strict "refs"</CODE>. So instead of $var, use <CODE>${'var'}</CODE>.</P>
<PRE>
local $var = "global";
my $var = "lexical";</PRE>
<PRE>
print "lexical is $var\n";</PRE>
<PRE>
no strict 'refs';
print "global is ${'var'}\n";</PRE>
<P>If you know your package, you can just mention it explicitly, as in
$Some_Pack::var. Note that the notation $::var is <EM>not</EM> the dynamic
$var in the current package, but rather the one in the <CODE>main</CODE>
package, as though you had written $main::var. Specifying the package
directly makes you hard-code its name, but it executes faster and
avoids running afoul of <CODE>use strict "refs"</CODE>.</P>
<P>
<H2><A NAME="what's the difference between deep and shallow binding">What's the difference between deep and shallow binding?</A></H2>
<P>In deep binding, lexical variables mentioned in anonymous subroutines
are the same ones that were in scope when the subroutine was created.
In shallow binding, they are whichever variables with the same names
happen to be in scope when the subroutine is called. Perl always uses
deep binding of lexical variables (i.e., those created with my()).
However, dynamic variables (aka global, local, or package variables)
are effectively shallowly bound. Consider this just one more reason
not to use them. See the answer to <A HREF="#what's a closure">What's a closure?</A>.</P>
<P>
<H2><A NAME="why doesn't my($foo) = <file>; work right">Why doesn't ``my($foo) = <FILE>;'' work right?</A></H2>
<P><A HREF="../../lib/Pod/perlfunc.html#item_my"><CODE>my()</CODE></A> and <A HREF="../../lib/Pod/perlfunc.html#item_local"><CODE>local()</CODE></A> give list context to the right hand side
of <CODE>=</CODE>. The <FH> read operation, like so many of Perl's
functions and operators, can tell which context it was called in and
behaves appropriately. In general, the <A HREF="../../lib/Pod/perlfunc.html#item_scalar"><CODE>scalar()</CODE></A> function can help.
This function does nothing to the data itself (contrary to popular myth)
but rather tells its argument to behave in whatever its scalar fashion is.
If that function doesn't have a defined scalar behavior, this of course
doesn't help you (such as with sort()).</P>
<P>To enforce scalar context in this particular case, however, you need
merely omit the parentheses:</P>
<PRE>
local($foo) = <FILE>; # WRONG
local($foo) = scalar(<FILE>); # ok
local $foo = <FILE>; # right</PRE>
<P>You should probably be using lexical variables anyway, although the
issue is the same here:</P>
<PRE>
my($foo) = <FILE>; # WRONG
my $foo = <FILE>; # right</PRE>
<P>
<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>
<P>Why do you want to do that? :-)</P>
<P>If you want to override a predefined function, such as open(),
then you'll have to import the new definition from a different
module. See <A HREF="../../lib/Pod/perlsub.html#overriding builtin functions">Overriding Built-in Functions in the perlsub manpage</A>. There's
also an example in <A HREF="../../lib/Pod/perltoot.html#class::template">Class::Template in the perltoot manpage</A>.</P>
<P>If you want to overload a Perl operator, such as <CODE>+</CODE> or <CODE>**</CODE>,
then you'll want to use the <CODE>use overload</CODE> pragma, documented
in <A HREF="../../lib/overload.html">the overload manpage</A>.</P>
<P>If you're talking about obscuring method calls in parent classes,
see <A HREF="../../lib/Pod/perltoot.html#overridden methods">Overridden Methods in the perltoot manpage</A>.</P>
<P>
<H2><A NAME="what's the difference between calling a function as &foo and foo()">What's the difference between calling a function as &foo and foo()?</A></H2>
<P>When you call a function as <CODE>&foo</CODE>, you allow that function access to
your current @_ values, and you by-pass prototypes. That means that
the function doesn't get an empty @_, it gets yours! While not
strictly speaking a bug (it's documented that way in <A HREF="../../lib/Pod/perlsub.html">the perlsub manpage</A>), it
would be hard to consider this a feature in most cases.</P>
<P>When you call your function as <CODE>&foo()</CODE>, then you <EM>do</EM> get a new @_,
but prototyping is still circumvented.</P>
<P>Normally, you want to call a function using <CODE>foo()</CODE>. You may only
omit the parentheses if the function is already known to the compiler
because it already saw the definition (<A HREF="../../lib/Pod/perlfunc.html#item_use"><CODE>use</CODE></A> but not <A HREF="../../lib/Pod/perlfunc.html#item_require"><CODE>require</CODE></A>),
or via a forward reference or <CODE>use subs</CODE> declaration. Even in this
case, you get a clean @_ without any of the old values leaking through
where they don't belong.</P>
<P>
<H2><A NAME="how do i create a switch or case statement">How do I create a switch or case statement?</A></H2>
<P>This is explained in more depth in the <A HREF="../../lib/Pod/perlsyn.html">the perlsyn manpage</A>. Briefly, there's
no official case statement, because of the variety of tests possible
in Perl (numeric comparison, string comparison, glob comparison,
regex matching, overloaded comparisons, ...). Larry couldn't decide
how best to do this, so he left it out, even though it's been on the
wish list since perl1.</P>
<P>The general answer is to write a construct like this:</P>
<PRE>
for ($variable_to_test) {
if (/pat1/) { } # do something
elsif (/pat2/) { } # do something else
elsif (/pat3/) { } # do something else
else { } # default
}</PRE>
<P>Here's a simple example of a switch based on pattern matching, this
time lined up in a way to make it look more like a switch statement.
We'll do a multi-way conditional based on the type of reference stored
in $whatchamacallit:</P>
<PRE>
SWITCH: for (ref $whatchamacallit) {</PRE>
<PRE>
/^$/ && die "not a reference";</PRE>
<PRE>
/SCALAR/ && do {
print_scalar($$ref);
last SWITCH;
};</PRE>
<PRE>
/ARRAY/ && do {
print_array(@$ref);
last SWITCH;
};</PRE>
<PRE>
/HASH/ && do {
print_hash(%$ref);
last SWITCH;
};</PRE>
<PRE>
/CODE/ && do {
warn "can't print function ref";
last SWITCH;
};</PRE>
<PRE>
# DEFAULT</PRE>
<PRE>
warn "User defined type skipped";</PRE>
<PRE>
}</PRE>
<P>See <CODE>perlsyn/"Basic BLOCKs and Switch Statements"</CODE> for many other
examples in this style.</P>
<P>Sometimes you should change the positions of the constant and the variable.
For example, let's say you wanted to test which of many answers you were
given, but in a case-insensitive way that also allows abbreviations.
You can use the following technique if the strings all start with
different characters, or if you want to arrange the matches so that
one takes precedence over another, as <CODE>"SEND"</CODE> has precedence over
<CODE>"STOP"</CODE> here:</P>
<PRE>
chomp($answer = <>);
if ("SEND" =~ /^\Q$answer/i) { print "Action is send\n" }
elsif ("STOP" =~ /^\Q$answer/i) { print "Action is stop\n" }
elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" }
elsif ("LIST" =~ /^\Q$answer/i) { print "Action is list\n" }
elsif ("EDIT" =~ /^\Q$answer/i) { print "Action is edit\n" }</PRE>
<P>A totally different approach is to create a hash of function references.</P>
<PRE>
my %commands = (
"happy" => \&joy,
"sad", => \&sullen,
"done" => sub { die "See ya!" },
"mad" => \&angry,
);</PRE>
<PRE>
print "How are you? ";
chomp($string = <STDIN>);
if ($commands{$string}) {
$commands{$string}->();
} else {
print "No such command: $string\n";
}</PRE>
<P>
<H2><A NAME="how can i catch accesses to undefined variables/functions/methods">How can I catch accesses to undefined variables/functions/methods?</A></H2>
<P>The AUTOLOAD method, discussed in <A HREF="../../lib/Pod/perlsub.html#autoloading">Autoloading in the perlsub manpage</A> and
<A HREF="../../lib/Pod/perltoot.html#autoload: proxy methods">AUTOLOAD: Proxy Methods in the perltoot manpage</A>, lets you capture calls to
undefined functions and methods.</P>
<P>When it comes to undefined variables that would trigger a warning
under <CODE>-w</CODE>, you can use a handler to trap the pseudo-signal
<CODE>__WARN__</CODE> like this:</P>
<PRE>
$SIG{__WARN__} = sub {</PRE>
<PRE>
for ( $_[0] ) { # voici un switch statement</PRE>
<PRE>
/Use of uninitialized value/ && do {
# promote warning to a fatal
die $_;
};</PRE>
<PRE>
# other warning cases to catch could go here;</PRE>
<PRE>
warn $_;
}</PRE>
<PRE>
};</PRE>
<P>
<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>
<P>Some possible reasons: your inheritance is getting confused, you've
misspelled the method name, or the object is of the wrong type. Check
out <A HREF="../../lib/Pod/perltoot.html">the perltoot manpage</A> for details on these. You may also use <A HREF="../../lib/Pod/perlfunc.html#item_ref"><CODE>print
ref($object)</CODE></A> to find out the class <CODE>$object</CODE> was blessed into.</P>
<P>Another possible reason for problems is because you've used the
indirect object syntax (eg, <CODE>find Guru "Samy"</CODE>) on a class name
before Perl has seen that such a package exists. It's wisest to make
sure your packages are all defined before you start using them, which
will be taken care of if you use the <A HREF="../../lib/Pod/perlfunc.html#item_use"><CODE>use</CODE></A> statement instead of
<A HREF="../../lib/Pod/perlfunc.html#item_require"><CODE>require</CODE></A>. If not, make sure to use arrow notation (eg,
<CODE>Guru->find("Samy")</CODE>) instead. Object notation is explained in