1N/A=head1 NAME
1N/A
1N/Aperlfaq7 - General Perl Language Issues ($Revision: 1.15 $, $Date: 2003/07/24 02:17:21 $)
1N/A
1N/A=head1 DESCRIPTION
1N/A
1N/AThis section deals with general Perl language issues that don't
1N/Aclearly fit into any of the other sections.
1N/A
1N/A=head2 Can I get a BNF/yacc/RE for the Perl language?
1N/A
1N/AThere is no BNF, but you can paw your way through the yacc grammar in
1N/Aperly.y in the source distribution if you're particularly brave. The
1N/Agrammar relies on very smart tokenizing code, so be prepared to
1N/Aventure into toke.c as well.
1N/A
1N/AIn the words of Chaim Frenkel: "Perl's grammar can not be reduced to BNF.
1N/AThe work of parsing perl is distributed between yacc, the lexer, smoke
1N/Aand mirrors."
1N/A
1N/A=head2 What are all these $@%&* punctuation signs, and how do I know when to use them?
1N/A
1N/AThey are type specifiers, as detailed in L<perldata>:
1N/A
1N/A $ for scalar values (number, string or reference)
1N/A @ for arrays
1N/A % for hashes (associative arrays)
1N/A & for subroutines (aka functions, procedures, methods)
1N/A * for all types of that symbol name. In version 4 you used them like
1N/A pointers, but in modern perls you can just use references.
1N/A
1N/AThere are couple of other symbols that you're likely to encounter that aren't
1N/Areally type specifiers:
1N/A
1N/A <> are used for inputting a record from a filehandle.
1N/A \ takes a reference to something.
1N/A
1N/ANote that <FILE> is I<neither> the type specifier for files
1N/Anor the name of the handle. It is the C<< <> >> operator applied
1N/Ato the handle FILE. It reads one line (well, record--see
1N/AL<perlvar/$E<sol>>) from the handle FILE in scalar context, or I<all> lines
1N/Ain list context. When performing open, close, or any other operation
1N/Abesides C<< <> >> on files, or even when talking about the handle, do
1N/AI<not> use the brackets. These are correct: C<eof(FH)>, C<seek(FH, 0,
1N/A2)> and "copying from STDIN to FILE".
1N/A
1N/A=head2 Do I always/never have to quote my strings or use semicolons and commas?
1N/A
1N/ANormally, a bareword doesn't need to be quoted, but in most cases
1N/Aprobably should be (and must be under C<use strict>). But a hash key
1N/Aconsisting of a simple word (that isn't the name of a defined
1N/Asubroutine) and the left-hand operand to the C<< => >> operator both
1N/Acount as though they were quoted:
1N/A
1N/A This is like this
1N/A ------------ ---------------
1N/A $foo{line} $foo{"line"}
1N/A bar => stuff "bar" => stuff
1N/A
1N/AThe final semicolon in a block is optional, as is the final comma in a
1N/Alist. Good style (see L<perlstyle>) says to put them in except for
1N/Aone-liners:
1N/A
1N/A if ($whoops) { exit 1 }
1N/A @nums = (1, 2, 3);
1N/A
1N/A if ($whoops) {
1N/A exit 1;
1N/A }
1N/A @lines = (
1N/A "There Beren came from mountains cold",
1N/A "And lost he wandered under leaves",
1N/A );
1N/A
1N/A=head2 How do I skip some return values?
1N/A
1N/AOne way is to treat the return values as a list and index into it:
1N/A
1N/A $dir = (getpwnam($user))[7];
1N/A
1N/AAnother way is to use undef as an element on the left-hand-side:
1N/A
1N/A ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
1N/A
1N/AYou can also use a list slice to select only the elements that
1N/Ayou need:
1N/A
1N/A ($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5];
1N/A
1N/A=head2 How do I temporarily block warnings?
1N/A
1N/AIf you are running Perl 5.6.0 or better, the C<use warnings> pragma
1N/Aallows fine control of what warning are produced.
1N/ASee L<perllexwarn> for more details.
1N/A
1N/A {
1N/A no warnings; # temporarily turn off warnings
1N/A $a = $b + $c; # I know these might be undef
1N/A }
1N/A
1N/AIf you have an older version of Perl, the C<$^W> variable (documented
1N/Ain L<perlvar>) controls runtime warnings for a block:
1N/A
1N/A {
1N/A local $^W = 0; # temporarily turn off warnings
1N/A $a = $b + $c; # I know these might be undef
1N/A }
1N/A
1N/ANote that like all the punctuation variables, you cannot currently
1N/Ause my() on C<$^W>, only local().
1N/A
1N/A=head2 What's an extension?
1N/A
1N/AAn extension is a way of calling compiled C code from Perl. Reading
1N/AL<perlxstut> is a good place to learn more about extensions.
1N/A
1N/A=head2 Why do Perl operators have different precedence than C operators?
1N/A
1N/AActually, they don't. All C operators that Perl copies have the same
1N/Aprecedence in Perl as they do in C. The problem is with operators that C
1N/Adoesn't have, especially functions that give a list context to everything
1N/Aon their right, eg. print, chmod, exec, and so on. Such functions are
1N/Acalled "list operators" and appear as such in the precedence table in
1N/AL<perlop>.
1N/A
1N/AA common mistake is to write:
1N/A
1N/A unlink $file || die "snafu";
1N/A
1N/AThis gets interpreted as:
1N/A
1N/A unlink ($file || die "snafu");
1N/A
1N/ATo avoid this problem, either put in extra parentheses or use the
1N/Asuper low precedence C<or> operator:
1N/A
1N/A (unlink $file) || die "snafu";
1N/A unlink $file or die "snafu";
1N/A
1N/AThe "English" operators (C<and>, C<or>, C<xor>, and C<not>)
1N/Adeliberately have precedence lower than that of list operators for
1N/Ajust such situations as the one above.
1N/A
1N/AAnother operator with surprising precedence is exponentiation. It
1N/Abinds more tightly even than unary minus, making C<-2**2> product a
1N/Anegative not a positive four. It is also right-associating, meaning
1N/Athat C<2**3**2> is two raised to the ninth power, not eight squared.
1N/A
1N/AAlthough it has the same precedence as in C, Perl's C<?:> operator
1N/Aproduces an lvalue. This assigns $x to either $a or $b, depending
1N/Aon the trueness of $maybe:
1N/A
1N/A ($maybe ? $a : $b) = $x;
1N/A
1N/A=head2 How do I declare/create a structure?
1N/A
1N/AIn general, you don't "declare" a structure. Just use a (probably
1N/Aanonymous) hash reference. See L<perlref> and L<perldsc> for details.
1N/AHere's an example:
1N/A
1N/A $person = {}; # new anonymous hash
1N/A $person->{AGE} = 24; # set field AGE to 24
1N/A $person->{NAME} = "Nat"; # set field NAME to "Nat"
1N/A
1N/AIf you're looking for something a bit more rigorous, try L<perltoot>.
1N/A
1N/A=head2 How do I create a module?
1N/A
1N/AA module is a package that lives in a file of the same name. For
1N/Aexample, the Hello::There module would live in Hello/There.pm. For
1N/Adetails, read L<perlmod>. You'll also find L<Exporter> helpful. If
1N/Ayou're writing a C or mixed-language module with both C and Perl, then
1N/Ayou should study L<perlxstut>.
1N/A
1N/AThe C<h2xs> program will create stubs for all the important stuff for you:
1N/A
1N/A % h2xs -XA -n My::Module
1N/A
1N/AThe C<-X> switch tells C<h2xs> that you are not using C<XS> extension
1N/Acode. The C<-A> switch tells C<h2xs> that you are not using the
1N/AAutoLoader, and the C<-n> switch specifies the name of the module.
1N/ASee L<h2xs> for more details.
1N/A
1N/A=head2 How do I create a class?
1N/A
1N/ASee L<perltoot> for an introduction to classes and objects, as well as
1N/AL<perlobj> and L<perlbot>.
1N/A
1N/A=head2 How can I tell if a variable is tainted?
1N/A
1N/AYou can use the tainted() function of the Scalar::Util module, available
1N/Afrom CPAN (or included with Perl since release 5.8.0).
1N/ASee also L<perlsec/"Laundering and Detecting Tainted Data">.
1N/A
1N/A=head2 What's a closure?
1N/A
1N/AClosures are documented in L<perlref>.
1N/A
1N/AI<Closure> is a computer science term with a precise but
1N/Ahard-to-explain meaning. Closures are implemented in Perl as anonymous
1N/Asubroutines with lasting references to lexical variables outside their
1N/Aown scopes. These lexicals magically refer to the variables that were
1N/Aaround when the subroutine was defined (deep binding).
1N/A
1N/AClosures make sense in any programming language where you can have the
1N/Areturn value of a function be itself a function, as you can in Perl.
1N/ANote that some languages provide anonymous functions but are not
1N/Acapable of providing proper closures: the Python language, for
1N/Aexample. For more information on closures, check out any textbook on
1N/Afunctional programming. Scheme is a language that not only supports
1N/Abut encourages closures.
1N/A
1N/AHere's a classic function-generating function:
1N/A
1N/A sub add_function_generator {
1N/A return sub { shift + shift };
1N/A }
1N/A
1N/A $add_sub = add_function_generator();
1N/A $sum = $add_sub->(4,5); # $sum is 9 now.
1N/A
1N/AThe closure works as a I<function template> with some customization
1N/Aslots left out to be filled later. The anonymous subroutine returned
1N/Aby add_function_generator() isn't technically a closure because it
1N/Arefers to no lexicals outside its own scope.
1N/A
1N/AContrast this with the following make_adder() function, in which the
1N/Areturned anonymous function contains a reference to a lexical variable
1N/Aoutside the scope of that function itself. Such a reference requires
1N/Athat Perl return a proper closure, thus locking in for all time the
1N/Avalue that the lexical had when the function was created.
1N/A
1N/A sub make_adder {
1N/A my $addpiece = shift;
1N/A return sub { shift + $addpiece };
1N/A }
1N/A
1N/A $f1 = make_adder(20);
1N/A $f2 = make_adder(555);
1N/A
1N/ANow C<&$f1($n)> is always 20 plus whatever $n you pass in, whereas
1N/AC<&$f2($n)> is always 555 plus whatever $n you pass in. The $addpiece
1N/Ain the closure sticks around.
1N/A
1N/AClosures are often used for less esoteric purposes. For example, when
1N/Ayou want to pass in a bit of code into a function:
1N/A
1N/A my $line;
1N/A timeout( 30, sub { $line = <STDIN> } );
1N/A
1N/AIf the code to execute had been passed in as a string,
1N/AC<< '$line = <STDIN>' >>, there would have been no way for the
1N/Ahypothetical timeout() function to access the lexical variable
1N/A$line back in its caller's scope.
1N/A
1N/A=head2 What is variable suicide and how can I prevent it?
1N/A
1N/AVariable suicide is when you (temporarily or permanently) lose the
1N/Avalue of a variable. It is caused by scoping through my() and local()
1N/Ainteracting with either closures or aliased foreach() iterator
1N/Avariables and subroutine arguments. It used to be easy to
1N/Ainadvertently lose a variable's value this way, but now it's much
1N/Aharder. Take this code:
1N/A
1N/A my $f = "foo";
1N/A sub T {
1N/A while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" }
1N/A }
1N/A T;
1N/A print "Finally $f\n";
1N/A
1N/AThe $f that has "bar" added to it three times should be a new C<$f>
1N/A(C<my $f> should create a new local variable each time through the loop).
1N/AIt isn't, however. This was a bug, now fixed in the latest releases
1N/A(tested against 5.004_05, 5.005_03, and 5.005_56).
1N/A
1N/A=head2 How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?
1N/A
1N/AWith the exception of regexes, you need to pass references to these
1N/Aobjects. See L<perlsub/"Pass by Reference"> for this particular
1N/Aquestion, and L<perlref> for information on references.
1N/A
1N/ASee ``Passing Regexes'', below, for information on passing regular
1N/Aexpressions.
1N/A
1N/A=over 4
1N/A
1N/A=item Passing Variables and Functions
1N/A
1N/ARegular variables and functions are quite easy to pass: just pass in a
1N/Areference to an existing or anonymous variable or function:
1N/A
1N/A func( \$some_scalar );
1N/A
1N/A func( \@some_array );
1N/A func( [ 1 .. 10 ] );
1N/A
1N/A func( \%some_hash );
1N/A func( { this => 10, that => 20 } );
1N/A
1N/A func( \&some_func );
1N/A func( sub { $_[0] ** $_[1] } );
1N/A
1N/A=item Passing Filehandles
1N/A
1N/AAs of Perl 5.6, you can represent filehandles with scalar variables
1N/Awhich you treat as any other scalar.
1N/A
1N/A open my $fh, $filename or die "Cannot open $filename! $!";
1N/A func( $fh );
1N/A
1N/A sub func {
1N/A my $passed_fh = shift;
1N/A
1N/A my $line = <$fh>;
1N/A }
1N/A
1N/ABefore Perl 5.6, you had to use the C<*FH> or C<\*FH> notations.
1N/AThese are "typeglobs"--see L<perldata/"Typeglobs and Filehandles">
1N/Aand especially L<perlsub/"Pass by Reference"> for more information.
1N/A
1N/A=item Passing Regexes
1N/A
1N/ATo pass regexes around, you'll need to be using a release of Perl
1N/Asufficiently recent as to support the C<qr//> construct, pass around
1N/Astrings and use an exception-trapping eval, or else be very, very clever.
1N/A
1N/AHere's an example of how to pass in a string to be regex compared
1N/Ausing C<qr//>:
1N/A
1N/A sub compare($$) {
1N/A my ($val1, $regex) = @_;
1N/A my $retval = $val1 =~ /$regex/;
1N/A return $retval;
1N/A }
1N/A $match = compare("old McDonald", qr/d.*D/i);
1N/A
1N/ANotice how C<qr//> allows flags at the end. That pattern was compiled
1N/Aat compile time, although it was executed later. The nifty C<qr//>
1N/Anotation wasn't introduced until the 5.005 release. Before that, you
1N/Ahad to approach this problem much less intuitively. For example, here
1N/Ait is again if you don't have C<qr//>:
1N/A
1N/A sub compare($$) {
1N/A my ($val1, $regex) = @_;
1N/A my $retval = eval { $val1 =~ /$regex/ };
1N/A die if $@;
1N/A return $retval;
1N/A }
1N/A
1N/A $match = compare("old McDonald", q/($?i)d.*D/);
1N/A
1N/AMake sure you never say something like this:
1N/A
1N/A return eval "\$val =~ /$regex/"; # WRONG
1N/A
1N/Aor someone can sneak shell escapes into the regex due to the double
1N/Ainterpolation of the eval and the double-quoted string. For example:
1N/A
1N/A $pattern_of_evil = 'danger ${ system("rm -rf * &") } danger';
1N/A
1N/A eval "\$string =~ /$pattern_of_evil/";
1N/A
1N/AThose preferring to be very, very clever might see the O'Reilly book,
1N/AI<Mastering Regular Expressions>, by Jeffrey Friedl. Page 273's
1N/ABuild_MatchMany_Function() is particularly interesting. A complete
1N/Acitation of this book is given in L<perlfaq2>.
1N/A
1N/A=item Passing Methods
1N/A
1N/ATo pass an object method into a subroutine, you can do this:
1N/A
1N/A call_a_lot(10, $some_obj, "methname")
1N/A sub call_a_lot {
1N/A my ($count, $widget, $trick) = @_;
1N/A for (my $i = 0; $i < $count; $i++) {
1N/A $widget->$trick();
1N/A }
1N/A }
1N/A
1N/AOr, you can use a closure to bundle up the object, its
1N/Amethod call, and arguments:
1N/A
1N/A my $whatnot = sub { $some_obj->obfuscate(@args) };
1N/A func($whatnot);
1N/A sub func {
1N/A my $code = shift;
1N/A &$code();
1N/A }
1N/A
1N/AYou could also investigate the can() method in the UNIVERSAL class
1N/A(part of the standard perl distribution).
1N/A
1N/A=back
1N/A
1N/A=head2 How do I create a static variable?
1N/A
1N/AAs with most things in Perl, TMTOWTDI. What is a "static variable" in
1N/Aother languages could be either a function-private variable (visible
1N/Aonly within a single function, retaining its value between calls to
1N/Athat function), or a file-private variable (visible only to functions
1N/Awithin the file it was declared in) in Perl.
1N/A
1N/AHere's code to implement a function-private variable:
1N/A
1N/A BEGIN {
1N/A my $counter = 42;
1N/A sub prev_counter { return --$counter }
1N/A sub next_counter { return $counter++ }
1N/A }
1N/A
1N/ANow prev_counter() and next_counter() share a private variable $counter
1N/Athat was initialized at compile time.
1N/A
1N/ATo declare a file-private variable, you'll still use a my(), putting
1N/Athe declaration at the outer scope level at the top of the file.
1N/AAssume this is in file Pax.pm:
1N/A
1N/A package Pax;
1N/A my $started = scalar(localtime(time()));
1N/A
1N/A sub begun { return $started }
1N/A
1N/AWhen C<use Pax> or C<require Pax> loads this module, the variable will
1N/Abe initialized. It won't get garbage-collected the way most variables
1N/Agoing out of scope do, because the begun() function cares about it,
1N/Abut no one else can get it. It is not called $Pax::started because
1N/Aits scope is unrelated to the package. It's scoped to the file. You
1N/Acould conceivably have several packages in that same file all
1N/Aaccessing the same private variable, but another file with the same
1N/Apackage couldn't get to it.
1N/A
1N/ASee L<perlsub/"Persistent Private Variables"> for details.
1N/A
1N/A=head2 What's the difference between dynamic and lexical (static) scoping? Between local() and my()?
1N/A
1N/AC<local($x)> saves away the old value of the global variable C<$x>
1N/Aand assigns a new value for the duration of the subroutine I<which is
1N/Avisible in other functions called from that subroutine>. This is done
1N/Aat run-time, so is called dynamic scoping. local() always affects global
1N/Avariables, also called package variables or dynamic variables.
1N/A
1N/AC<my($x)> creates a new variable that is only visible in the current
1N/Asubroutine. This is done at compile-time, so it is called lexical or
1N/Astatic scoping. my() always affects private variables, also called
1N/Alexical variables or (improperly) static(ly scoped) variables.
1N/A
1N/AFor instance:
1N/A
1N/A sub visible {
1N/A print "var has value $var\n";
1N/A }
1N/A
1N/A sub dynamic {
1N/A local $var = 'local'; # new temporary value for the still-global
1N/A visible(); # variable called $var
1N/A }
1N/A
1N/A sub lexical {
1N/A my $var = 'private'; # new private variable, $var
1N/A visible(); # (invisible outside of sub scope)
1N/A }
1N/A
1N/A $var = 'global';
1N/A
1N/A visible(); # prints global
1N/A dynamic(); # prints local
1N/A lexical(); # prints global
1N/A
1N/ANotice how at no point does the value "private" get printed. That's
1N/Abecause $var only has that value within the block of the lexical()
1N/Afunction, and it is hidden from called subroutine.
1N/A
1N/AIn summary, local() doesn't make what you think of as private, local
1N/Avariables. It gives a global variable a temporary value. my() is
1N/Awhat you're looking for if you want private variables.
1N/A
1N/ASee L<perlsub/"Private Variables via my()"> and
1N/AL<perlsub/"Temporary Values via local()"> for excruciating details.
1N/A
1N/A=head2 How can I access a dynamic variable while a similarly named lexical is in scope?
1N/A
1N/AIf you know your package, you can just mention it explicitly, as in
1N/A$Some_Pack::var. Note that the notation $::var is B<not> the dynamic $var
1N/Ain the current package, but rather the one in the "main" package, as
1N/Athough you had written $main::var.
1N/A
1N/A use vars '$var';
1N/A local $var = "global";
1N/A my $var = "lexical";
1N/A
1N/A print "lexical is $var\n";
1N/A print "global is $main::var\n";
1N/A
1N/AAlternatively you can use the compiler directive our() to bring a
1N/Adynamic variable into the current lexical scope.
1N/A
1N/A require 5.006; # our() did not exist before 5.6
1N/A use vars '$var';
1N/A
1N/A local $var = "global";
1N/A my $var = "lexical";
1N/A
1N/A print "lexical is $var\n";
1N/A
1N/A {
1N/A our $var;
1N/A print "global is $var\n";
1N/A }
1N/A
1N/A=head2 What's the difference between deep and shallow binding?
1N/A
1N/AIn deep binding, lexical variables mentioned in anonymous subroutines
1N/Aare the same ones that were in scope when the subroutine was created.
1N/AIn shallow binding, they are whichever variables with the same names
1N/Ahappen to be in scope when the subroutine is called. Perl always uses
1N/Adeep binding of lexical variables (i.e., those created with my()).
1N/AHowever, dynamic variables (aka global, local, or package variables)
1N/Aare effectively shallowly bound. Consider this just one more reason
1N/Anot to use them. See the answer to L<"What's a closure?">.
1N/A
1N/A=head2 Why doesn't "my($foo) = E<lt>FILEE<gt>;" work right?
1N/A
1N/AC<my()> and C<local()> give list context to the right hand side
1N/Aof C<=>. The <FH> read operation, like so many of Perl's
1N/Afunctions and operators, can tell which context it was called in and
1N/Abehaves appropriately. In general, the scalar() function can help.
1N/AThis function does nothing to the data itself (contrary to popular myth)
1N/Abut rather tells its argument to behave in whatever its scalar fashion is.
1N/AIf that function doesn't have a defined scalar behavior, this of course
1N/Adoesn't help you (such as with sort()).
1N/A
1N/ATo enforce scalar context in this particular case, however, you need
1N/Amerely omit the parentheses:
1N/A
1N/A local($foo) = <FILE>; # WRONG
1N/A local($foo) = scalar(<FILE>); # ok
1N/A local $foo = <FILE>; # right
1N/A
1N/AYou should probably be using lexical variables anyway, although the
1N/Aissue is the same here:
1N/A
1N/A my($foo) = <FILE>; # WRONG
1N/A my $foo = <FILE>; # right
1N/A
1N/A=head2 How do I redefine a builtin function, operator, or method?
1N/A
1N/AWhy do you want to do that? :-)
1N/A
1N/AIf you want to override a predefined function, such as open(),
1N/Athen you'll have to import the new definition from a different
1N/Amodule. See L<perlsub/"Overriding Built-in Functions">. There's
1N/Aalso an example in L<perltoot/"Class::Template">.
1N/A
1N/AIf you want to overload a Perl operator, such as C<+> or C<**>,
1N/Athen you'll want to use the C<use overload> pragma, documented
1N/Ain L<overload>.
1N/A
1N/AIf you're talking about obscuring method calls in parent classes,
1N/Asee L<perltoot/"Overridden Methods">.
1N/A
1N/A=head2 What's the difference between calling a function as &foo and foo()?
1N/A
1N/AWhen you call a function as C<&foo>, you allow that function access to
1N/Ayour current @_ values, and you bypass prototypes.
1N/AThe function doesn't get an empty @_--it gets yours! While not
1N/Astrictly speaking a bug (it's documented that way in L<perlsub>), it
1N/Awould be hard to consider this a feature in most cases.
1N/A
1N/AWhen you call your function as C<&foo()>, then you I<do> get a new @_,
1N/Abut prototyping is still circumvented.
1N/A
1N/ANormally, you want to call a function using C<foo()>. You may only
1N/Aomit the parentheses if the function is already known to the compiler
1N/Abecause it already saw the definition (C<use> but not C<require>),
1N/Aor via a forward reference or C<use subs> declaration. Even in this
1N/Acase, you get a clean @_ without any of the old values leaking through
1N/Awhere they don't belong.
1N/A
1N/A=head2 How do I create a switch or case statement?
1N/A
1N/AThis is explained in more depth in the L<perlsyn>. Briefly, there's
1N/Ano official case statement, because of the variety of tests possible
1N/Ain Perl (numeric comparison, string comparison, glob comparison,
1N/Aregex matching, overloaded comparisons, ...).
1N/ALarry couldn't decide how best to do this, so he left it out, even
1N/Athough it's been on the wish list since perl1.
1N/A
1N/AStarting from Perl 5.8 to get switch and case one can use the
1N/ASwitch extension and say:
1N/A
1N/A use Switch;
1N/A
1N/Aafter which one has switch and case. It is not as fast as it could be
1N/Abecause it's not really part of the language (it's done using source
1N/Afilters) but it is available, and it's very flexible.
1N/A
1N/ABut if one wants to use pure Perl, the general answer is to write a
1N/Aconstruct like this:
1N/A
1N/A for ($variable_to_test) {
1N/A if (/pat1/) { } # do something
1N/A elsif (/pat2/) { } # do something else
1N/A elsif (/pat3/) { } # do something else
1N/A else { } # default
1N/A }
1N/A
1N/AHere's a simple example of a switch based on pattern matching, this
1N/Atime lined up in a way to make it look more like a switch statement.
1N/AWe'll do a multiway conditional based on the type of reference stored
1N/Ain $whatchamacallit:
1N/A
1N/A SWITCH: for (ref $whatchamacallit) {
1N/A
1N/A /^$/ && die "not a reference";
1N/A
1N/A /SCALAR/ && do {
1N/A print_scalar($$ref);
1N/A last SWITCH;
1N/A };
1N/A
1N/A /ARRAY/ && do {
1N/A print_array(@$ref);
1N/A last SWITCH;
1N/A };
1N/A
1N/A /HASH/ && do {
1N/A print_hash(%$ref);
1N/A last SWITCH;
1N/A };
1N/A
1N/A /CODE/ && do {
1N/A warn "can't print function ref";
1N/A last SWITCH;
1N/A };
1N/A
1N/A # DEFAULT
1N/A
1N/A warn "User defined type skipped";
1N/A
1N/A }
1N/A
1N/ASee C<perlsyn/"Basic BLOCKs and Switch Statements"> for many other
1N/Aexamples in this style.
1N/A
1N/ASometimes you should change the positions of the constant and the variable.
1N/AFor example, let's say you wanted to test which of many answers you were
1N/Agiven, but in a case-insensitive way that also allows abbreviations.
1N/AYou can use the following technique if the strings all start with
1N/Adifferent characters or if you want to arrange the matches so that
1N/Aone takes precedence over another, as C<"SEND"> has precedence over
1N/AC<"STOP"> here:
1N/A
1N/A chomp($answer = <>);
1N/A if ("SEND" =~ /^\Q$answer/i) { print "Action is send\n" }
1N/A elsif ("STOP" =~ /^\Q$answer/i) { print "Action is stop\n" }
1N/A elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" }
1N/A elsif ("LIST" =~ /^\Q$answer/i) { print "Action is list\n" }
1N/A elsif ("EDIT" =~ /^\Q$answer/i) { print "Action is edit\n" }
1N/A
1N/AA totally different approach is to create a hash of function references.
1N/A
1N/A my %commands = (
1N/A "happy" => \&joy,
1N/A "sad", => \&sullen,
1N/A "done" => sub { die "See ya!" },
1N/A "mad" => \&angry,
1N/A );
1N/A
1N/A print "How are you? ";
1N/A chomp($string = <STDIN>);
1N/A if ($commands{$string}) {
1N/A $commands{$string}->();
1N/A } else {
1N/A print "No such command: $string\n";
1N/A }
1N/A
1N/A=head2 How can I catch accesses to undefined variables, functions, or methods?
1N/A
1N/AThe AUTOLOAD method, discussed in L<perlsub/"Autoloading"> and
1N/AL<perltoot/"AUTOLOAD: Proxy Methods">, lets you capture calls to
1N/Aundefined functions and methods.
1N/A
1N/AWhen it comes to undefined variables that would trigger a warning
1N/Aunder C<use warnings>, you can promote the warning to an error.
1N/A
1N/A use warnings FATAL => qw(uninitialized);
1N/A
1N/A=head2 Why can't a method included in this same file be found?
1N/A
1N/ASome possible reasons: your inheritance is getting confused, you've
1N/Amisspelled the method name, or the object is of the wrong type. Check
1N/Aout L<perltoot> for details about any of the above cases. You may
1N/Aalso use C<print ref($object)> to find out the class C<$object> was
1N/Ablessed into.
1N/A
1N/AAnother possible reason for problems is because you've used the
1N/Aindirect object syntax (eg, C<find Guru "Samy">) on a class name
1N/Abefore Perl has seen that such a package exists. It's wisest to make
1N/Asure your packages are all defined before you start using them, which
1N/Awill be taken care of if you use the C<use> statement instead of
1N/AC<require>. If not, make sure to use arrow notation (eg.,
1N/AC<< Guru->find("Samy") >>) instead. Object notation is explained in
1N/AL<perlobj>.
1N/A
1N/AMake sure to read about creating modules in L<perlmod> and
1N/Athe perils of indirect objects in L<perlobj/"Method Invocation">.
1N/A
1N/A=head2 How can I find out my current package?
1N/A
1N/AIf you're just a random program, you can do this to find
1N/Aout what the currently compiled package is:
1N/A
1N/A my $packname = __PACKAGE__;
1N/A
1N/ABut, if you're a method and you want to print an error message
1N/Athat includes the kind of object you were called on (which is
1N/Anot necessarily the same as the one in which you were compiled):
1N/A
1N/A sub amethod {
1N/A my $self = shift;
1N/A my $class = ref($self) || $self;
1N/A warn "called me from a $class object";
1N/A }
1N/A
1N/A=head2 How can I comment out a large block of perl code?
1N/A
1N/AYou can use embedded POD to discard it. Enclose the blocks you want
1N/Ato comment out in POD markers, for example C<=for nobody> and C<=cut>
1N/A(which marks ends of POD blocks).
1N/A
1N/A # program is here
1N/A
1N/A =for nobody
1N/A
1N/A all of this stuff
1N/A
1N/A here will be ignored
1N/A by everyone
1N/A
1N/A =cut
1N/A
1N/A # program continues
1N/A
1N/AThe pod directives cannot go just anywhere. You must put a
1N/Apod directive where the parser is expecting a new statement,
1N/Anot just in the middle of an expression or some other
1N/Aarbitrary grammar production.
1N/A
1N/ASee L<perlpod> for more details.
1N/A
1N/A=head2 How do I clear a package?
1N/A
1N/AUse this code, provided by Mark-Jason Dominus:
1N/A
1N/A sub scrub_package {
1N/A no strict 'refs';
1N/A my $pack = shift;
1N/A die "Shouldn't delete main package"
1N/A if $pack eq "" || $pack eq "main";
1N/A my $stash = *{$pack . '::'}{HASH};
1N/A my $name;
1N/A foreach $name (keys %$stash) {
1N/A my $fullname = $pack . '::' . $name;
1N/A # Get rid of everything with that name.
1N/A undef $$fullname;
1N/A undef @$fullname;
1N/A undef %$fullname;
1N/A undef &$fullname;
1N/A undef *$fullname;
1N/A }
1N/A }
1N/A
1N/AOr, if you're using a recent release of Perl, you can
1N/Ajust use the Symbol::delete_package() function instead.
1N/A
1N/A=head2 How can I use a variable as a variable name?
1N/A
1N/ABeginners often think they want to have a variable contain the name
1N/Aof a variable.
1N/A
1N/A $fred = 23;
1N/A $varname = "fred";
1N/A ++$$varname; # $fred now 24
1N/A
1N/AThis works I<sometimes>, but it is a very bad idea for two reasons.
1N/A
1N/AThe first reason is that this technique I<only works on global
1N/Avariables>. That means that if $fred is a lexical variable created
1N/Awith my() in the above example, the code wouldn't work at all: you'd
1N/Aaccidentally access the global and skip right over the private lexical
1N/Aaltogether. Global variables are bad because they can easily collide
1N/Aaccidentally and in general make for non-scalable and confusing code.
1N/A
1N/ASymbolic references are forbidden under the C<use strict> pragma.
1N/AThey are not true references and consequently are not reference counted
1N/Aor garbage collected.
1N/A
1N/AThe other reason why using a variable to hold the name of another
1N/Avariable is a bad idea is that the question often stems from a lack of
1N/Aunderstanding of Perl data structures, particularly hashes. By using
1N/Asymbolic references, you are just using the package's symbol-table hash
1N/A(like C<%main::>) instead of a user-defined hash. The solution is to
1N/Ause your own hash or a real reference instead.
1N/A
1N/A $USER_VARS{"fred"} = 23;
1N/A $varname = "fred";
1N/A $USER_VARS{$varname}++; # not $$varname++
1N/A
1N/AThere we're using the %USER_VARS hash instead of symbolic references.
1N/ASometimes this comes up in reading strings from the user with variable
1N/Areferences and wanting to expand them to the values of your perl
1N/Aprogram's variables. This is also a bad idea because it conflates the
1N/Aprogram-addressable namespace and the user-addressable one. Instead of
1N/Areading a string and expanding it to the actual contents of your program's
1N/Aown variables:
1N/A
1N/A $str = 'this has a $fred and $barney in it';
1N/A $str =~ s/(\$\w+)/$1/eeg; # need double eval
1N/A
1N/Ait would be better to keep a hash around like %USER_VARS and have
1N/Avariable references actually refer to entries in that hash:
1N/A
1N/A $str =~ s/\$(\w+)/$USER_VARS{$1}/g; # no /e here at all
1N/A
1N/AThat's faster, cleaner, and safer than the previous approach. Of course,
1N/Ayou don't need to use a dollar sign. You could use your own scheme to
1N/Amake it less confusing, like bracketed percent symbols, etc.
1N/A
1N/A $str = 'this has a %fred% and %barney% in it';
1N/A $str =~ s/%(\w+)%/$USER_VARS{$1}/g; # no /e here at all
1N/A
1N/AAnother reason that folks sometimes think they want a variable to
1N/Acontain the name of a variable is because they don't know how to build
1N/Aproper data structures using hashes. For example, let's say they
1N/Awanted two hashes in their program: %fred and %barney, and that they
1N/Awanted to use another scalar variable to refer to those by name.
1N/A
1N/A $name = "fred";
1N/A $$name{WIFE} = "wilma"; # set %fred
1N/A
1N/A $name = "barney";
1N/A $$name{WIFE} = "betty"; # set %barney
1N/A
1N/AThis is still a symbolic reference, and is still saddled with the
1N/Aproblems enumerated above. It would be far better to write:
1N/A
1N/A $folks{"fred"}{WIFE} = "wilma";
1N/A $folks{"barney"}{WIFE} = "betty";
1N/A
1N/AAnd just use a multilevel hash to start with.
1N/A
1N/AThe only times that you absolutely I<must> use symbolic references are
1N/Awhen you really must refer to the symbol table. This may be because it's
1N/Asomething that can't take a real reference to, such as a format name.
1N/ADoing so may also be important for method calls, since these always go
1N/Athrough the symbol table for resolution.
1N/A
1N/AIn those cases, you would turn off C<strict 'refs'> temporarily so you
1N/Acan play around with the symbol table. For example:
1N/A
1N/A @colors = qw(red blue green yellow orange purple violet);
1N/A for my $name (@colors) {
1N/A no strict 'refs'; # renege for the block
1N/A *$name = sub { "<FONT COLOR='$name'>@_</FONT>" };
1N/A }
1N/A
1N/AAll those functions (red(), blue(), green(), etc.) appear to be separate,
1N/Abut the real code in the closure actually was compiled only once.
1N/A
1N/ASo, sometimes you might want to use symbolic references to directly
1N/Amanipulate the symbol table. This doesn't matter for formats, handles, and
1N/Asubroutines, because they are always global--you can't use my() on them.
1N/AFor scalars, arrays, and hashes, though--and usually for subroutines--
1N/Ayou probably only want to use hard references.
1N/A
1N/A=head2 What does "bad interpreter" mean?
1N/A
1N/AThe "bad interpreter" message comes from the shell, not perl. The
1N/Aactual message may vary depending on your platform, shell, and locale
1N/Asettings.
1N/A
1N/AIf you see "bad interpreter - no such file or directory", the first
1N/Aline in your perl script (the "shebang" line) does not contain the
1N/Aright path to perl (or any other program capable of running scripts).
1N/ASometimes this happens when you move the script from one machine to
1N/Aanother and each machine has a different path to perl---/usr/bin/perl
1N/Aversus /usr/local/bin/perl for instance.
1N/A
1N/AIf you see "bad interpreter: Permission denied", you need to make your
1N/Ascript executable.
1N/A
1N/AIn either case, you should still be able to run the scripts with perl
1N/Aexplicitly:
1N/A
1N/A % perl script.pl
1N/A
1N/AIf you get a message like "perl: command not found", perl is not in
1N/Ayour PATH, which might also mean that the location of perl is not
1N/Awhere you expect it so you need to adjust your shebang line.
1N/A
1N/A=head1 AUTHOR AND COPYRIGHT
1N/A
1N/ACopyright (c) 1997-2002 Tom Christiansen and Nathan Torkington.
1N/AAll rights reserved.
1N/A
1N/AThis documentation is free; you can redistribute it and/or modify it
1N/Aunder the same terms as Perl itself.
1N/A
1N/AIrrespective of its distribution, all code examples in this file
1N/Aare hereby placed into the public domain. You are permitted and
1N/Aencouraged to use this code in your own programs for fun
1N/Aor for profit as you see fit. A simple comment in the code giving
1N/Acredit would be courteous but is not required.
1N/A