.\" -*- mode: troff; coding: utf-8 -*- .\" Automatically generated by Pod::Man 5.01 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>. .ie n \{\ . ds C` "" . ds C' "" 'br\} .el\{\ . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "PERLFAQ7 1" .TH PERLFAQ7 1 2023-11-28 "perl v5.38.2" "Perl Programmers Reference Guide" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME perlfaq7 \- General Perl Language Issues .SH VERSION .IX Header "VERSION" version 5.20210520 .SH DESCRIPTION .IX Header "DESCRIPTION" This section deals with general Perl language issues that don't clearly fit into any of the other sections. .SS "Can I get a BNF/yacc/RE for the Perl language?" .IX Subsection "Can I get a BNF/yacc/RE for the Perl language?" 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. .PP 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." .SS "What are all these $@%&* punctuation signs, and how do I know when to use them?" .IX Subsection "What are all these $@%&* punctuation signs, and how do I know when to use them?" They are type specifiers, as detailed in perldata: .PP .Vb 6 \& $ 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. .Ve .PP There are a couple of other symbols that you're likely to encounter that aren't really type specifiers: .PP .Vb 2 \& <> are used for inputting a record from a filehandle. \& \e takes a reference to something. .Ve .PP Note that is \fIneither\fR the type specifier for files nor the name of the handle. It is the \f(CW\*(C`<>\*(C'\fR operator applied to the handle FILE. It reads one line (well, record\-\-see "$/" in perlvar) from the handle FILE in scalar context, or \fIall\fR lines in list context. When performing open, close, or any other operation besides \f(CW\*(C`<>\*(C'\fR on files, or even when talking about the handle, do \&\fInot\fR use the brackets. These are correct: \f(CWeof(FH)\fR, \f(CW\*(C`seek(FH, 0, 2)\*(C'\fR and "copying from STDIN to FILE". .SS "Do I always/never have to quote my strings or use semicolons and commas?" .IX Subsection "Do I always/never have to quote my strings or use semicolons and commas?" Normally, a bareword doesn't need to be quoted, but in most cases probably should be (and must be under \f(CW\*(C`use strict\*(C'\fR). But a hash key consisting of a simple word and the left-hand operand to the \f(CW\*(C`=>\*(C'\fR operator both count as though they were quoted: .PP .Vb 4 \& This is like this \& \-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \& $foo{line} $foo{\*(Aqline\*(Aq} \& bar => stuff \*(Aqbar\*(Aq => stuff .Ve .PP The final semicolon in a block is optional, as is the final comma in a list. Good style (see perlstyle) says to put them in except for one-liners: .PP .Vb 2 \& if ($whoops) { exit 1 } \& my @nums = (1, 2, 3); \& \& if ($whoops) { \& exit 1; \& } \& \& my @lines = ( \& "There Beren came from mountains cold", \& "And lost he wandered under leaves", \& ); .Ve .SS "How do I skip some return values?" .IX Subsection "How do I skip some return values?" One way is to treat the return values as a list and index into it: .PP .Vb 1 \& $dir = (getpwnam($user))[7]; .Ve .PP Another way is to use undef as an element on the left-hand-side: .PP .Vb 1 \& ($dev, $ino, undef, undef, $uid, $gid) = stat($file); .Ve .PP You can also use a list slice to select only the elements that you need: .PP .Vb 1 \& ($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5]; .Ve .SS "How do I temporarily block warnings?" .IX Subsection "How do I temporarily block warnings?" If you are running Perl 5.6.0 or better, the \f(CW\*(C`use warnings\*(C'\fR pragma allows fine control of what warnings are produced. See perllexwarn for more details. .PP .Vb 4 \& { \& no warnings; # temporarily turn off warnings \& $x = $y + $z; # I know these might be undef \& } .Ve .PP Additionally, you can enable and disable categories of warnings. You turn off the categories you want to ignore and you can still get other categories of warnings. See perllexwarn for the complete details, including the category names and hierarchy. .PP .Vb 4 \& { \& no warnings \*(Aquninitialized\*(Aq; \& $x = $y + $z; \& } .Ve .PP If you have an older version of Perl, the \f(CW$^W\fR variable (documented in perlvar) controls runtime warnings for a block: .PP .Vb 4 \& { \& local $^W = 0; # temporarily turn off warnings \& $x = $y + $z; # I know these might be undef \& } .Ve .PP Note that like all the punctuation variables, you cannot currently use \fBmy()\fR on \f(CW$^W\fR, only \fBlocal()\fR. .SS "What's an extension?" .IX Subsection "What's an extension?" An extension is a way of calling compiled C code from Perl. Reading perlxstut is a good place to learn more about extensions. .SS "Why do Perl operators have different precedence than C operators?" .IX Subsection "Why do Perl operators have different precedence than C operators?" 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 perlop. .PP A common mistake is to write: .PP .Vb 1 \& unlink $file || die "snafu"; .Ve .PP This gets interpreted as: .PP .Vb 1 \& unlink ($file || die "snafu"); .Ve .PP To avoid this problem, either put in extra parentheses or use the super low precedence \f(CW\*(C`or\*(C'\fR operator: .PP .Vb 2 \& (unlink $file) || die "snafu"; \& unlink $file or die "snafu"; .Ve .PP The "English" operators (\f(CW\*(C`and\*(C'\fR, \f(CW\*(C`or\*(C'\fR, \f(CW\*(C`xor\*(C'\fR, and \f(CW\*(C`not\*(C'\fR) deliberately have precedence lower than that of list operators for just such situations as the one above. .PP Another operator with surprising precedence is exponentiation. It binds more tightly even than unary minus, making \f(CW\*(C`\-2**2\*(C'\fR produce a negative four and not a positive one. It is also right-associating, meaning that \f(CW\*(C`2**3**2\*(C'\fR is two raised to the ninth power, not eight squared. .PP Although it has the same precedence as in C, Perl's \f(CW\*(C`?:\*(C'\fR operator produces an lvalue. This assigns \f(CW$x\fR to either \f(CW$if_true\fR or \f(CW$if_false\fR, depending on the trueness of \f(CW$maybe:\fR .PP .Vb 1 \& ($maybe ? $if_true : $if_false) = $x; .Ve .SS "How do I declare/create a structure?" .IX Subsection "How do I declare/create a structure?" In general, you don't "declare" a structure. Just use a (probably anonymous) hash reference. See perlref and perldsc for details. Here's an example: .PP .Vb 3 \& $person = {}; # new anonymous hash \& $person\->{AGE} = 24; # set field AGE to 24 \& $person\->{NAME} = "Nat"; # set field NAME to "Nat" .Ve .PP If you're looking for something a bit more rigorous, try perlootut. .SS "How do I create a module?" .IX Subsection "How do I create a module?" perlnewmod is a good place to start, ignore the bits about uploading to CPAN if you don't want to make your module publicly available. .PP ExtUtils::ModuleMaker and Module::Starter are also good places to start. Many CPAN authors now use Dist::Zilla to automate as much as possible. .PP Detailed documentation about modules can be found at: perlmod, perlmodlib, perlmodstyle. .PP If you need to include C code or C library interfaces use h2xs. h2xs will create the module distribution structure and the initial interface files. perlxs and perlxstut explain the details. .SS "How do I adopt or take over a module already on CPAN?" .IX Subsection "How do I adopt or take over a module already on CPAN?" Ask the current maintainer to make you a co-maintainer or transfer the module to you. .PP If you can not reach the author for some reason contact the PAUSE admins at modules@perl.org who may be able to help, but each case is treated separately. .IP \(bu 4 Get a login for the Perl Authors Upload Server (PAUSE) if you don't already have one: .IP \(bu 4 Write to modules@perl.org explaining what you did to contact the current maintainer. The PAUSE admins will also try to reach the maintainer. .IP \(bu 4 Post a public message in a heavily trafficked site announcing your intention to take over the module. .IP \(bu 4 Wait a bit. The PAUSE admins don't want to act too quickly in case the current maintainer is on holiday. If there's no response to private communication or the public post, a PAUSE admin can transfer it to you. .SS "How do I create a class?" .IX Xref "class, creation package" .IX Subsection "How do I create a class?" (contributed by brian d foy) .PP In Perl, a class is just a package, and methods are just subroutines. Perl doesn't get more formal than that and lets you set up the package just the way that you like it (that is, it doesn't set up anything for you). .PP See also perlootut, a tutorial that covers class creation, and perlobj. .SS "How can I tell if a variable is tainted?" .IX Subsection "How can I tell if a variable is tainted?" You can use the \fBtainted()\fR function of the Scalar::Util module, available from CPAN (or included with Perl since release 5.8.0). See also "Laundering and Detecting Tainted Data" in perlsec. .SS "What's a closure?" .IX Subsection "What's a closure?" Closures are documented in perlref. .PP \&\fIClosure\fR is a computer science term with a precise but hard-to-explain meaning. Usually, 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). .PP Closures are most often used in programming languages 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. .PP Here's a classic non-closure function-generating function: .PP .Vb 3 \& sub add_function_generator { \& return sub { shift() + shift() }; \& } \& \& my $add_sub = add_function_generator(); \& my $sum = $add_sub\->(4,5); # $sum is 9 now. .Ve .PP The anonymous subroutine returned by \fBadd_function_generator()\fR isn't technically a closure because it refers to no lexicals outside its own scope. Using a closure gives you a \fIfunction template\fR with some customization slots left out to be filled later. .PP Contrast this with the following \fBmake_adder()\fR 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. .PP .Vb 4 \& sub make_adder { \& my $addpiece = shift; \& return sub { shift() + $addpiece }; \& } \& \& my $f1 = make_adder(20); \& my $f2 = make_adder(555); .Ve .PP Now \f(CW$f1\->($n)\fR is always 20 plus whatever \f(CW$n\fR you pass in, whereas \&\f(CW$f2\->($n)\fR is always 555 plus whatever \f(CW$n\fR you pass in. The \f(CW$addpiece\fR in the closure sticks around. .PP Closures are often used for less esoteric purposes. For example, when you want to pass in a bit of code into a function: .PP .Vb 2 \& my $line; \& timeout( 30, sub { $line = } ); .Ve .PP If the code to execute had been passed in as a string, \&\f(CW\*(Aq$line = \*(Aq\fR, there would have been no way for the hypothetical \fBtimeout()\fR function to access the lexical variable \&\f(CW$line\fR back in its caller's scope. .PP Another use for a closure is to make a variable \fIprivate\fR to a named subroutine, e.g. a counter that gets initialized at creation time of the sub and can only be modified from within the sub. This is sometimes used with a BEGIN block in package files to make sure a variable doesn't get meddled with during the lifetime of the package: .PP .Vb 4 \& BEGIN { \& my $id = 0; \& sub next_id { ++$id } \& } .Ve .PP This is discussed in more detail in perlsub; see the entry on \&\fIPersistent Private Variables\fR. .SS "What is variable suicide and how can I prevent it?" .IX Subsection "What is variable suicide and how can I prevent it?" This problem was fixed in perl 5.004_05, so preventing it means upgrading your version of perl. ;) .PP Variable suicide is when you (temporarily or permanently) lose the value of a variable. It is caused by scoping through \fBmy()\fR and \fBlocal()\fR interacting with either closures or aliased \fBforeach()\fR 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: .PP .Vb 4 \& my $f = \*(Aqfoo\*(Aq; \& sub T { \& while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\en" } \& } \& \& T; \& print "Finally $f\en"; .Ve .PP If you are experiencing variable suicide, that \f(CW\*(C`my $f\*(C'\fR in the subroutine doesn't pick up a fresh copy of the \f(CW$f\fR whose value is \f(CW\*(Aqfoo\*(Aq\fR. The output shows that inside the subroutine the value of \f(CW$f\fR leaks through when it shouldn't, as in this output: .PP .Vb 4 \& foobar \& foobarbar \& foobarbarbar \& Finally foo .Ve .PP The \f(CW$f\fR that has "bar" added to it three times should be a new \f(CW$f\fR \&\f(CW\*(C`my $f\*(C'\fR should create a new lexical variable each time through the loop. The expected output is: .PP .Vb 4 \& foobar \& foobar \& foobar \& Finally foo .Ve .SS "How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?" .IX Subsection "How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?" You need to pass references to these objects. See "Pass by Reference" in perlsub for this particular question, and perlref for information on references. .IP "Passing Variables and Functions" 4 .IX Item "Passing Variables and Functions" Regular variables and functions are quite easy to pass: just pass in a reference to an existing or anonymous variable or function: .Sp .Vb 1 \& func( \e$some_scalar ); \& \& func( \e@some_array ); \& func( [ 1 .. 10 ] ); \& \& func( \e%some_hash ); \& func( { this => 10, that => 20 } ); \& \& func( \e&some_func ); \& func( sub { $_[0] ** $_[1] } ); .Ve .IP "Passing Filehandles" 4 .IX Item "Passing Filehandles" As of Perl 5.6, you can represent filehandles with scalar variables which you treat as any other scalar. .Sp .Vb 2 \& open my $fh, $filename or die "Cannot open $filename! $!"; \& func( $fh ); \& \& sub func { \& my $passed_fh = shift; \& \& my $line = <$passed_fh>; \& } .Ve .Sp Before Perl 5.6, you had to use the \f(CW*FH\fR or \f(CW\*(C`\e*FH\*(C'\fR notations. These are "typeglobs"\-\-see "Typeglobs and Filehandles" in perldata and especially "Pass by Reference" in perlsub for more information. .IP "Passing Regexes" 4 .IX Item "Passing Regexes" Here's an example of how to pass in a string and a regular expression for it to match against. You construct the pattern with the \f(CW\*(C`qr//\*(C'\fR operator: .Sp .Vb 6 \& sub compare { \& my ($val1, $regex) = @_; \& my $retval = $val1 =~ /$regex/; \& return $retval; \& } \& $match = compare("old McDonald", qr/d.*D/i); .Ve .IP "Passing Methods" 4 .IX Item "Passing Methods" To pass an object method into a subroutine, you can do this: .Sp .Vb 7 \& call_a_lot(10, $some_obj, "methname") \& sub call_a_lot { \& my ($count, $widget, $trick) = @_; \& for (my $i = 0; $i < $count; $i++) { \& $widget\->$trick(); \& } \& } .Ve .Sp Or, you can use a closure to bundle up the object, its method call, and arguments: .Sp .Vb 6 \& my $whatnot = sub { $some_obj\->obfuscate(@args) }; \& func($whatnot); \& sub func { \& my $code = shift; \& &$code(); \& } .Ve .Sp You could also investigate the \fBcan()\fR method in the UNIVERSAL class (part of the standard perl distribution). .SS "How do I create a static variable?" .IX Subsection "How do I create a static variable?" (contributed by brian d foy) .PP In Perl 5.10, declare the variable with \f(CW\*(C`state\*(C'\fR. The \f(CW\*(C`state\*(C'\fR declaration creates the lexical variable that persists between calls to the subroutine: .PP .Vb 1 \& sub counter { state $count = 1; $count++ } .Ve .PP You can fake a static variable by using a lexical variable which goes out of scope. In this example, you define the subroutine \f(CW\*(C`counter\*(C'\fR, and it uses the lexical variable \f(CW$count\fR. Since you wrap this in a BEGIN block, \f(CW$count\fR is defined at compile-time, but also goes out of scope at the end of the BEGIN block. The BEGIN block also ensures that the subroutine and the value it uses is defined at compile-time so the subroutine is ready to use just like any other subroutine, and you can put this code in the same place as other subroutines in the program text (i.e. at the end of the code, typically). The subroutine \&\f(CW\*(C`counter\*(C'\fR still has a reference to the data, and is the only way you can access the value (and each time you do, you increment the value). The data in chunk of memory defined by \f(CW$count\fR is private to \&\f(CW\*(C`counter\*(C'\fR. .PP .Vb 4 \& BEGIN { \& my $count = 1; \& sub counter { $count++ } \& } \& \& my $start = counter(); \& \& .... # code that calls counter(); \& \& my $end = counter(); .Ve .PP In the previous example, you created a function-private variable because only one function remembered its reference. You could define multiple functions while the variable is in scope, and each function can share the "private" variable. It's not really "static" because you can access it outside the function while the lexical variable is in scope, and even create references to it. In this example, \&\f(CW\*(C`increment_count\*(C'\fR and \f(CW\*(C`return_count\*(C'\fR share the variable. One function adds to the value and the other simply returns the value. They can both access \f(CW$count\fR, and since it has gone out of scope, there is no other way to access it. .PP .Vb 5 \& BEGIN { \& my $count = 1; \& sub increment_count { $count++ } \& sub return_count { $count } \& } .Ve .PP To declare a file-private variable, you still use a lexical variable. A file is also a scope, so a lexical variable defined in the file cannot be seen from any other file. .PP See "Persistent Private Variables" in perlsub for more information. The discussion of closures in perlref may help you even though we did not use anonymous subroutines in this answer. See "Persistent Private Variables" in perlsub for details. .SS "What's the difference between dynamic and lexical (static) scoping? Between \fBlocal()\fP and \fBmy()\fP?" .IX Subsection "What's the difference between dynamic and lexical (static) scoping? Between local() and my()?" \&\f(CWlocal($x)\fR saves away the old value of the global variable \f(CW$x\fR and assigns a new value for the duration of the subroutine \fIwhich is visible in other functions called from that subroutine\fR. This is done at run-time, so is called dynamic scoping. \fBlocal()\fR always affects global variables, also called package variables or dynamic variables. .PP \&\f(CWmy($x)\fR creates a new variable that is only visible in the current subroutine. This is done at compile-time, so it is called lexical or static scoping. \fBmy()\fR always affects private variables, also called lexical variables or (improperly) static(ly scoped) variables. .PP For instance: .PP .Vb 3 \& sub visible { \& print "var has value $var\en"; \& } \& \& sub dynamic { \& local $var = \*(Aqlocal\*(Aq; # new temporary value for the still\-global \& visible(); # variable called $var \& } \& \& sub lexical { \& my $var = \*(Aqprivate\*(Aq; # new private variable, $var \& visible(); # (invisible outside of sub scope) \& } \& \& $var = \*(Aqglobal\*(Aq; \& \& visible(); # prints global \& dynamic(); # prints local \& lexical(); # prints global .Ve .PP Notice how at no point does the value "private" get printed. That's because \f(CW$var\fR only has that value within the block of the \fBlexical()\fR function, and it is hidden from the called subroutine. .PP In summary, \fBlocal()\fR doesn't make what you think of as private, local variables. It gives a global variable a temporary value. \fBmy()\fR is what you're looking for if you want private variables. .PP See "Private Variables via \fBmy()\fR" in perlsub and "Temporary Values via \fBlocal()\fR" in perlsub for excruciating details. .SS "How can I access a dynamic variable while a similarly named lexical is in scope?" .IX Subsection "How can I access a dynamic variable while a similarly named lexical is in scope?" If you know your package, you can just mention it explicitly, as in \&\f(CW$Some_Pack::var\fR. Note that the notation \f(CW$::var\fR is \fBnot\fR the dynamic \f(CW$var\fR in the current package, but rather the one in the "main" package, as though you had written \f(CW$main::var\fR. .PP .Vb 3 \& use vars \*(Aq$var\*(Aq; \& local $var = "global"; \& my $var = "lexical"; \& \& print "lexical is $var\en"; \& print "global is $main::var\en"; .Ve .PP Alternatively you can use the compiler directive \fBour()\fR to bring a dynamic variable into the current lexical scope. .PP .Vb 2 \& require 5.006; # our() did not exist before 5.6 \& use vars \*(Aq$var\*(Aq; \& \& local $var = "global"; \& my $var = "lexical"; \& \& print "lexical is $var\en"; \& \& { \& our $var; \& print "global is $var\en"; \& } .Ve .SS "What's the difference between deep and shallow binding?" .IX Subsection "What's the difference between deep and shallow binding?" 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 \fBmy()\fR). 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 "What's a closure?". .SS "Why doesn't ""my($foo) = <$fh>;"" work right?" .IX Subsection "Why doesn't ""my($foo) = <$fh>;"" work right?" \&\f(CWmy()\fR and \f(CWlocal()\fR give list context to the right hand side of \f(CW\*(C`=\*(C'\fR. 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 \fBscalar()\fR 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 \fBsort()\fR). .PP To enforce scalar context in this particular case, however, you need merely omit the parentheses: .PP .Vb 3 \& local($foo) = <$fh>; # WRONG \& local($foo) = scalar(<$fh>); # ok \& local $foo = <$fh>; # right .Ve .PP You should probably be using lexical variables anyway, although the issue is the same here: .PP .Vb 2 \& my($foo) = <$fh>; # WRONG \& my $foo = <$fh>; # right .Ve .SS "How do I redefine a builtin function, operator, or method?" .IX Subsection "How do I redefine a builtin function, operator, or method?" Why do you want to do that? :\-) .PP If you want to override a predefined function, such as \fBopen()\fR, then you'll have to import the new definition from a different module. See "Overriding Built-in Functions" in perlsub. .PP If you want to overload a Perl operator, such as \f(CW\*(C`+\*(C'\fR or \f(CW\*(C`**\*(C'\fR, then you'll want to use the \f(CW\*(C`use overload\*(C'\fR pragma, documented in overload. .PP If you're talking about obscuring method calls in parent classes, see "Overriding methods and method resolution" in perlootut. .SS "What's the difference between calling a function as &foo and \fBfoo()\fP?" .IX Subsection "What's the difference between calling a function as &foo and foo()?" (contributed by brian d foy) .PP Calling a subroutine as \f(CW&foo\fR with no trailing parentheses ignores the prototype of \f(CW\*(C`foo\*(C'\fR and passes it the current value of the argument list, \f(CW@_\fR. Here's an example; the \f(CW\*(C`bar\*(C'\fR subroutine calls \f(CW&foo\fR, which prints its arguments list: .PP .Vb 1 \& sub foo { print "Args in foo are: @_\en"; } \& \& sub bar { &foo; } \& \& bar( "a", "b", "c" ); .Ve .PP When you call \f(CW\*(C`bar\*(C'\fR with arguments, you see that \f(CW\*(C`foo\*(C'\fR got the same \f(CW@_\fR: .PP .Vb 1 \& Args in foo are: a b c .Ve .PP Calling the subroutine with trailing parentheses, with or without arguments, does not use the current \f(CW@_\fR. Changing the example to put parentheses after the call to \f(CW\*(C`foo\*(C'\fR changes the program: .PP .Vb 1 \& sub foo { print "Args in foo are: @_\en"; } \& \& sub bar { &foo(); } \& \& bar( "a", "b", "c" ); .Ve .PP Now the output shows that \f(CW\*(C`foo\*(C'\fR doesn't get the \f(CW@_\fR from its caller. .PP .Vb 1 \& Args in foo are: .Ve .PP However, using \f(CW\*(C`&\*(C'\fR in the call still overrides the prototype of \f(CW\*(C`foo\*(C'\fR if present: .PP .Vb 1 \& sub foo ($$$) { print "Args infoo are: @_\en"; } \& \& sub bar_1 { &foo; } \& sub bar_2 { &foo(); } \& sub bar_3 { foo( $_[0], $_[1], $_[2] ); } \& # sub bar_4 { foo(); } \& # bar_4 doesn\*(Aqt compile: "Not enough arguments for main::foo at ..." \& \& bar_1( "a", "b", "c" ); \& # Args in foo are: a b c \& \& bar_2( "a", "b", "c" ); \& # Args in foo are: \& \& bar_3( "a", "b", "c" ); \& # Args in foo are: a b c .Ve .PP The main use of the \f(CW@_\fR pass-through feature is to write subroutines whose main job it is to call other subroutines for you. For further details, see perlsub. .SS "How do I create a switch or case statement?" .IX Subsection "How do I create a switch or case statement?" There is a given/when statement in Perl, but it is experimental and likely to change in future. See perlsyn for more details. .PP The general answer is to use a CPAN module such as Switch::Plain: .PP .Vb 6 \& use Switch::Plain; \& sswitch($variable_holding_a_string) { \& case \*(Aqfirst\*(Aq: { } \& case \*(Aqsecond\*(Aq: { } \& default: { } \& } .Ve .PP or for more complicated comparisons, \f(CW\*(C`if\-elsif\-else\*(C'\fR: .PP .Vb 6 \& for ($variable_to_test) { \& if (/pat1/) { } # do something \& elsif (/pat2/) { } # do something else \& elsif (/pat3/) { } # do something else \& else { } # default \& } .Ve .PP Here's a simple example of a switch based on pattern matching, lined up in a way to make it look more like a switch statement. We'll do a multiway conditional based on the type of reference stored in \f(CW$whatchamacallit:\fR .PP .Vb 1 \& SWITCH: for (ref $whatchamacallit) { \& \& /^$/ && die "not a reference"; \& \& /SCALAR/ && do { \& print_scalar($$ref); \& last SWITCH; \& }; \& \& /ARRAY/ && do { \& print_array(@$ref); \& last SWITCH; \& }; \& \& /HASH/ && do { \& print_hash(%$ref); \& last SWITCH; \& }; \& \& /CODE/ && do { \& warn "can\*(Aqt print function ref"; \& last SWITCH; \& }; \& \& # DEFAULT \& \& warn "User defined type skipped"; \& \& } .Ve .PP See perlsyn for other examples in this style. .PP 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 \f(CW"SEND"\fR has precedence over \&\f(CW"STOP"\fR here: .PP .Vb 6 \& chomp($answer = <>); \& if ("SEND" =~ /^\eQ$answer/i) { print "Action is send\en" } \& elsif ("STOP" =~ /^\eQ$answer/i) { print "Action is stop\en" } \& elsif ("ABORT" =~ /^\eQ$answer/i) { print "Action is abort\en" } \& elsif ("LIST" =~ /^\eQ$answer/i) { print "Action is list\en" } \& elsif ("EDIT" =~ /^\eQ$answer/i) { print "Action is edit\en" } .Ve .PP A totally different approach is to create a hash of function references. .PP .Vb 6 \& my %commands = ( \& "happy" => \e&joy, \& "sad", => \e&sullen, \& "done" => sub { die "See ya!" }, \& "mad" => \e&angry, \& ); \& \& print "How are you? "; \& chomp($string = ); \& if ($commands{$string}) { \& $commands{$string}\->(); \& } else { \& print "No such command: $string\en"; \& } .Ve .PP Starting from Perl 5.8, a source filter module, \f(CW\*(C`Switch\*(C'\fR, can also be used to get switch and case. Its use is now discouraged, because it's not fully compatible with the native switch of Perl 5.10, and because, as it's implemented as a source filter, it doesn't always work as intended when complex syntax is involved. .SS "How can I catch accesses to undefined variables, functions, or methods?" .IX Subsection "How can I catch accesses to undefined variables, functions, or methods?" The AUTOLOAD method, discussed in "Autoloading" in perlsub lets you capture calls to undefined functions and methods. .PP When it comes to undefined variables that would trigger a warning under \f(CW\*(C`use warnings\*(C'\fR, you can promote the warning to an error. .PP .Vb 1 \& use warnings FATAL => qw(uninitialized); .Ve .SS "Why can't a method included in this same file be found?" .IX Subsection "Why can't a method included in this same file be found?" Some possible reasons: your inheritance is getting confused, you've misspelled the method name, or the object is of the wrong type. Check out perlootut for details about any of the above cases. You may also use \f(CW\*(C`print ref($object)\*(C'\fR to find out the class \f(CW$object\fR was blessed into. .PP Another possible reason for problems is that you've used the indirect object syntax (eg, \f(CW\*(C`find Guru "Samy"\*(C'\fR) 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 \f(CW\*(C`use\*(C'\fR statement instead of \&\f(CW\*(C`require\*(C'\fR. If not, make sure to use arrow notation (eg., \&\f(CW\*(C`Guru\->find("Samy")\*(C'\fR) instead. Object notation is explained in perlobj. .PP Make sure to read about creating modules in perlmod and the perils of indirect objects in "Method Invocation" in perlobj. .SS "How can I find out my current or calling package?" .IX Subsection "How can I find out my current or calling package?" (contributed by brian d foy) .PP To find the package you are currently in, use the special literal \&\f(CW\*(C`_\|_PACKAGE_\|_\*(C'\fR, as documented in perldata. You can only use the special literals as separate tokens, so you can't interpolate them into strings like you can with variables: .PP .Vb 2 \& my $current_package = _\|_PACKAGE_\|_; \& print "I am in package $current_package\en"; .Ve .PP If you want to find the package calling your code, perhaps to give better diagnostics as Carp does, use the \f(CW\*(C`caller\*(C'\fR built-in: .PP .Vb 3 \& sub foo { \& my @args = ...; \& my( $package, $filename, $line ) = caller; \& \& print "I was called from package $package\en"; \& ); .Ve .PP By default, your program starts in package \f(CW\*(C`main\*(C'\fR, so you will always be in some package. .PP This is different from finding out the package an object is blessed into, which might not be the current package. For that, use \f(CW\*(C`blessed\*(C'\fR from Scalar::Util, part of the Standard Library since Perl 5.8: .PP .Vb 2 \& use Scalar::Util qw(blessed); \& my $object_package = blessed( $object ); .Ve .PP Most of the time, you shouldn't care what package an object is blessed into, however, as long as it claims to inherit from that class: .PP .Vb 1 \& my $is_right_class = eval { $object\->isa( $package ) }; # true or false .Ve .PP And, with Perl 5.10 and later, you don't have to check for an inheritance to see if the object can handle a role. For that, you can use \f(CW\*(C`DOES\*(C'\fR, which comes from \f(CW\*(C`UNIVERSAL\*(C'\fR: .PP .Vb 1 \& my $class_does_it = eval { $object\->DOES( $role ) }; # true or false .Ve .PP You can safely replace \f(CW\*(C`isa\*(C'\fR with \f(CW\*(C`DOES\*(C'\fR (although the converse is not true). .SS "How can I comment out a large block of Perl code?" .IX Subsection "How can I comment out a large block of Perl code?" (contributed by brian d foy) .PP The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the \f(CW\*(C`#\*(C'\fR comments). You end the comment with \f(CW\*(C`=cut\*(C'\fR, ending the Pod section: .PP .Vb 1 \& =pod \& \& my $object = NotGonnaHappen\->new(); \& \& ignored_sub(); \& \& $wont_be_assigned = 37; \& \& =cut .Ve .PP The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well. .PP The \f(CW\*(C`=begin\*(C'\fR directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments with \f(CW\*(C`comment\*(C'\fR. End the comment using \f(CW\*(C`=end\*(C'\fR with the same label. You still need the \f(CW\*(C`=cut\*(C'\fR to go back to Perl code from the Pod comment: .PP .Vb 1 \& =begin comment \& \& my $object = NotGonnaHappen\->new(); \& \& ignored_sub(); \& \& $wont_be_assigned = 37; \& \& =end comment \& \& =cut .Ve .PP For more information on Pod, check out perlpod and perlpodspec. .SS "How do I clear a package?" .IX Subsection "How do I clear a package?" Use this code, provided by Mark-Jason Dominus: .PP .Vb 10 \& sub scrub_package { \& no strict \*(Aqrefs\*(Aq; \& my $pack = shift; \& die "Shouldn\*(Aqt delete main package" \& if $pack eq "" || $pack eq "main"; \& my $stash = *{$pack . \*(Aq::\*(Aq}{HASH}; \& my $name; \& foreach $name (keys %$stash) { \& my $fullname = $pack . \*(Aq::\*(Aq . $name; \& # Get rid of everything with that name. \& undef $$fullname; \& undef @$fullname; \& undef %$fullname; \& undef &$fullname; \& undef *$fullname; \& } \& } .Ve .PP Or, if you're using a recent release of Perl, you can just use the \fBSymbol::delete_package()\fR function instead. .SS "How can I use a variable as a variable name?" .IX Subsection "How can I use a variable as a variable name?" Beginners often think they want to have a variable contain the name of a variable. .PP .Vb 3 \& $fred = 23; \& $varname = "fred"; \& ++$$varname; # $fred now 24 .Ve .PP This works \fIsometimes\fR, but it is a very bad idea for two reasons. .PP The first reason is that this technique \fIonly works on global variables\fR. That means that if \f(CW$fred\fR is a lexical variable created with \fBmy()\fR in the above example, the code wouldn't work at all: you'd accidentally access the global and skip right over the private lexical altogether. Global variables are bad because they can easily collide accidentally and in general make for non-scalable and confusing code. .PP Symbolic references are forbidden under the \f(CW\*(C`use strict\*(C'\fR pragma. They are not true references and consequently are not reference-counted or garbage-collected. .PP The other reason why using a variable to hold the name of another variable is a bad idea is that the question often stems from a lack of understanding of Perl data structures, particularly hashes. By using symbolic references, you are just using the package's symbol-table hash (like \f(CW%main::\fR) instead of a user-defined hash. The solution is to use your own hash or a real reference instead. .PP .Vb 3 \& $USER_VARS{"fred"} = 23; \& my $varname = "fred"; \& $USER_VARS{$varname}++; # not $$varname++ .Ve .PP There we're using the \f(CW%USER_VARS\fR hash instead of symbolic references. Sometimes this comes up in reading strings from the user with variable references and wanting to expand them to the values of your perl program's variables. This is also a bad idea because it conflates the program-addressable namespace and the user-addressable one. Instead of reading a string and expanding it to the actual contents of your program's own variables: .PP .Vb 2 \& $str = \*(Aqthis has a $fred and $barney in it\*(Aq; \& $str =~ s/(\e$\ew+)/$1/eeg; # need double eval .Ve .PP it would be better to keep a hash around like \f(CW%USER_VARS\fR and have variable references actually refer to entries in that hash: .PP .Vb 1 \& $str =~ s/\e$(\ew+)/$USER_VARS{$1}/g; # no /e here at all .Ve .PP That's faster, cleaner, and safer than the previous approach. Of course, you don't need to use a dollar sign. You could use your own scheme to make it less confusing, like bracketed percent symbols, etc. .PP .Vb 2 \& $str = \*(Aqthis has a %fred% and %barney% in it\*(Aq; \& $str =~ s/%(\ew+)%/$USER_VARS{$1}/g; # no /e here at all .Ve .PP Another reason that folks sometimes think they want a variable to contain the name of a variable is that they don't know how to build proper data structures using hashes. For example, let's say they wanted two hashes in their program: \f(CW%fred\fR and \f(CW%barney\fR, and that they wanted to use another scalar variable to refer to those by name. .PP .Vb 2 \& $name = "fred"; \& $$name{WIFE} = "wilma"; # set %fred \& \& $name = "barney"; \& $$name{WIFE} = "betty"; # set %barney .Ve .PP This is still a symbolic reference, and is still saddled with the problems enumerated above. It would be far better to write: .PP .Vb 2 \& $folks{"fred"}{WIFE} = "wilma"; \& $folks{"barney"}{WIFE} = "betty"; .Ve .PP And just use a multilevel hash to start with. .PP The only times that you absolutely \fImust\fR use symbolic references are when you really must refer to the symbol table. This may be because it's something that one can't take a real reference to, such as a format name. Doing so may also be important for method calls, since these always go through the symbol table for resolution. .PP In those cases, you would turn off \f(CW\*(C`strict \*(Aqrefs\*(Aq\*(C'\fR temporarily so you can play around with the symbol table. For example: .PP .Vb 5 \& @colors = qw(red blue green yellow orange purple violet); \& for my $name (@colors) { \& no strict \*(Aqrefs\*(Aq; # renege for the block \& *$name = sub { "@_" }; \& } .Ve .PP All those functions (\fBred()\fR, \fBblue()\fR, \fBgreen()\fR, etc.) appear to be separate, but the real code in the closure actually was compiled only once. .PP So, sometimes you might want to use symbolic references to manipulate the symbol table directly. This doesn't matter for formats, handles, and subroutines, because they are always global\-\-you can't use \fBmy()\fR on them. For scalars, arrays, and hashes, though\-\-and usually for subroutines\-\- you probably only want to use hard references. .SS "What does ""bad interpreter"" mean?" .IX Subsection "What does ""bad interpreter"" mean?" (contributed by brian d foy) .PP The "bad interpreter" message comes from the shell, not perl. The actual message may vary depending on your platform, shell, and locale settings. .PP If you see "bad interpreter \- no such file or directory", the first line in your perl script (the "shebang" line) does not contain the right path to perl (or any other program capable of running scripts). Sometimes this happens when you move the script from one machine to another and each machine has a different path to perl\-\-/usr/bin/perl versus /usr/local/bin/perl for instance. It may also indicate that the source machine has CRLF line terminators and the destination machine has LF only: the shell tries to find /usr/bin/perl, but can't. .PP If you see "bad interpreter: Permission denied", you need to make your script executable. .PP In either case, you should still be able to run the scripts with perl explicitly: .PP .Vb 1 \& % perl script.pl .Ve .PP If you get a message like "perl: command not found", perl is not in your PATH, which might also mean that the location of perl is not where you expect it so you need to adjust your shebang line. .SS "Do I need to recompile XS modules when there is a change in the C library?" .IX Subsection "Do I need to recompile XS modules when there is a change in the C library?" (contributed by Alex Beamish) .PP If the new version of the C library is ABI-compatible (that's Application Binary Interface compatible) with the version you're upgrading from, and if the shared library version didn't change, no re-compilation should be necessary. .SH "AUTHOR AND COPYRIGHT" .IX Header "AUTHOR AND COPYRIGHT" Copyright (c) 1997\-2013 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved. .PP This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. .PP Irrespective of its distribution, all code examples in this file are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required.