{
    "mode": "man",
    "parameter": "PERLFAQ7",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/PERLFAQ7/1/json",
    "generated": "2026-10-04T09:16:44Z",
    "sections": {
        "NAME": {
            "content": "perlfaq7 - General Perl Language Issues\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version 5.20210520\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This section deals with general Perl language issues that don't clearly fit into any of the\nother sections.\n",
            "subsections": [
                {
                    "name": "Can I get a BNF/yacc/RE for the Perl language?",
                    "content": "There is no BNF, but you can paw your way through the yacc grammar in perly.y in the source\ndistribution if you're particularly brave. The grammar relies on very smart tokenizing code,\nso be prepared to venture into toke.c as well.\n\nIn the words of Chaim Frenkel: \"Perl's grammar can not be reduced to BNF.  The work of\nparsing perl is distributed between yacc, the lexer, smoke and mirrors.\"\n\nWhat are all these $@%&* punctuation signs, and how do I know when to use them?\nThey are type specifiers, as detailed in perldata:\n\n$ for scalar values (number, string or reference)\n@ for arrays\n% for hashes (associative arrays)\n& for subroutines (aka functions, procedures, methods)\n* for all types of that symbol name. In version 4 you used them like\npointers, but in modern perls you can just use references.\n\nThere are a couple of other symbols that you're likely to encounter that aren't really type\nspecifiers:\n\n<> are used for inputting a record from a filehandle.\n\\  takes a reference to something.\n\nNote that <FILE> is neither the type specifier for files nor the name of the handle. It is\nthe \"<>\" operator applied to the handle FILE. It reads one line (well, record--see \"$/\" in\nperlvar) from the handle FILE in scalar context, or all lines in list context. When\nperforming open, close, or any other operation besides \"<>\" on files, or even when talking\nabout the handle, do not use the brackets. These are correct: eof(FH), \"seek(FH, 0, 2)\" and\n\"copying from STDIN to FILE\".\n"
                },
                {
                    "name": "Do I always/never have to quote my strings or use semicolons and commas?",
                    "content": "Normally, a bareword doesn't need to be quoted, but in most cases probably should be (and\nmust be under \"use strict\"). But a hash key consisting of a simple word and the left-hand\noperand to the \"=>\" operator both count as though they were quoted:\n\nThis                    is like this\n------------            ---------------\n$foo{line}              $foo{'line'}\nbar => stuff            'bar' => stuff\n\nThe final semicolon in a block is optional, as is the final comma in a list. Good style (see\nperlstyle) says to put them in except for one-liners:\n\nif ($whoops) { exit 1 }\nmy @nums = (1, 2, 3);\n\nif ($whoops) {\nexit 1;\n}\n\nmy @lines = (\n\"There Beren came from mountains cold\",\n\"And lost he wandered under leaves\",\n);\n"
                },
                {
                    "name": "How do I skip some return values?",
                    "content": "One way is to treat the return values as a list and index into it:\n\n$dir = (getpwnam($user))[7];\n\nAnother way is to use undef as an element on the left-hand-side:\n\n($dev, $ino, undef, undef, $uid, $gid) = stat($file);\n\nYou can also use a list slice to select only the elements that you need:\n\n($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5];\n"
                },
                {
                    "name": "How do I temporarily block warnings?",
                    "content": "If you are running Perl 5.6.0 or better, the \"use warnings\" pragma allows fine control of\nwhat warnings are produced.  See perllexwarn for more details.\n\n{\nno warnings;          # temporarily turn off warnings\n$x = $y + $z;         # I know these might be undef\n}\n\nAdditionally, you can enable and disable categories of warnings.  You turn off the categories\nyou want to ignore and you can still get other categories of warnings. See perllexwarn for\nthe complete details, including the category names and hierarchy.\n\n{\nno warnings 'uninitialized';\n$x = $y + $z;\n}\n\nIf you have an older version of Perl, the $^W variable (documented in perlvar) controls\nruntime warnings for a block:\n\n{\nlocal $^W = 0;        # temporarily turn off warnings\n$x = $y + $z;         # I know these might be undef\n}\n\nNote that like all the punctuation variables, you cannot currently use my() on $^W, only\nlocal().\n"
                },
                {
                    "name": "What's an extension?",
                    "content": "An extension is a way of calling compiled C code from Perl. Reading perlxstut is a good place\nto learn more about extensions.\n"
                },
                {
                    "name": "Why do Perl operators have different precedence than C operators?",
                    "content": "Actually, they don't. All C operators that Perl copies have the same precedence in Perl as\nthey do in C. The problem is with operators that C doesn't have, especially functions that\ngive a list context to everything on their right, eg. print, chmod, exec, and so on. Such\nfunctions are called \"list operators\" and appear as such in the precedence table in perlop.\n\nA common mistake is to write:\n\nunlink $file || die \"snafu\";\n\nThis gets interpreted as:\n\nunlink ($file || die \"snafu\");\n\nTo avoid this problem, either put in extra parentheses or use the super low precedence \"or\"\noperator:\n\n(unlink $file) || die \"snafu\";\nunlink $file or die \"snafu\";\n\nThe \"English\" operators (\"and\", \"or\", \"xor\", and \"not\") deliberately have precedence lower\nthan that of list operators for just such situations as the one above.\n\nAnother operator with surprising precedence is exponentiation. It binds more tightly even\nthan unary minus, making \"-22\" produce a negative four and not a positive one. It is also\nright-associating, meaning that \"232\" is two raised to the ninth power, not eight\nsquared.\n\nAlthough it has the same precedence as in C, Perl's \"?:\" operator produces an lvalue. This\nassigns $x to either $iftrue or $iffalse, depending on the trueness of $maybe:\n\n($maybe ? $iftrue : $iffalse) = $x;\n"
                },
                {
                    "name": "How do I declare/create a structure?",
                    "content": "In general, you don't \"declare\" a structure. Just use a (probably anonymous) hash reference.\nSee perlref and perldsc for details.  Here's an example:\n\n$person = {};                   # new anonymous hash\n$person->{AGE}  = 24;           # set field AGE to 24\n$person->{NAME} = \"Nat\";        # set field NAME to \"Nat\"\n\nIf you're looking for something a bit more rigorous, try perlootut.\n"
                },
                {
                    "name": "How do I create a module?",
                    "content": "perlnewmod is a good place to start, ignore the bits about uploading to CPAN if you don't\nwant to make your module publicly available.\n\nExtUtils::ModuleMaker and Module::Starter are also good places to start. Many CPAN authors\nnow use Dist::Zilla to automate as much as possible.\n\nDetailed documentation about modules can be found at: perlmod, perlmodlib, perlmodstyle.\n\nIf you need to include C code or C library interfaces use h2xs. h2xs will create the module\ndistribution structure and the initial interface files.  perlxs and perlxstut explain the\ndetails.\n"
                },
                {
                    "name": "How do I adopt or take over a module already on CPAN?",
                    "content": "Ask the current maintainer to make you a co-maintainer or transfer the module to you.\n\nIf you can not reach the author for some reason contact the PAUSE admins at modules@perl.org\nwho may be able to help, but each case is treated separately.\n\n•   Get  a  login  for  the Perl Authors Upload Server (PAUSE) if you don't already have one:\n<http://pause.perl.org>\n\n•   Write to modules@perl.org explaining what you did to contact the current maintainer.  The\nPAUSE admins will also try to reach the maintainer.\n\n•   Post a public message in a heavily trafficked site announcing your intention to take over\nthe module.\n\n•   Wait a bit. The PAUSE admins don't want to act too quickly in case the current maintainer\nis  on  holiday.  If  there's  no response to private communication or the public post, a\nPAUSE admin can transfer it to you.\n"
                },
                {
                    "name": "How do I create a class?",
                    "content": "(contributed by brian d foy)\n\nIn Perl, a class is just a package, and methods are just subroutines.  Perl doesn't get  more\nformal  than  that and lets you set up the package just the way that you like it (that is, it\ndoesn't set up anything for you).\n\nSee also perlootut, a tutorial that covers class creation, and perlobj.\n"
                },
                {
                    "name": "How can I tell if a variable is tainted?",
                    "content": "You can use the tainted() function of  the  Scalar::Util  module,  available  from  CPAN  (or\nincluded with Perl since release 5.8.0).  See also \"Laundering and Detecting Tainted Data\" in\nperlsec.\n"
                },
                {
                    "name": "What's a closure?",
                    "content": "Closures are documented in perlref.\n\nClosure  is  a  computer  science  term  with a precise but hard-to-explain meaning. Usually,\nclosures are implemented in Perl as anonymous subroutines with lasting references to  lexical\nvariables outside their own scopes. These lexicals magically refer to the variables that were\naround when the subroutine was defined (deep binding).\n\nClosures  are most often used in programming languages where you can have the return value of\na function be itself a function, as you  can  in  Perl.  Note  that  some  languages  provide\nanonymous  functions  but  are not capable of providing proper closures: the Python language,\nfor example. For  more  information  on  closures,  check  out  any  textbook  on  functional\nprogramming. Scheme is a language that not only supports but encourages closures.\n\nHere's a classic non-closure function-generating function:\n\nsub addfunctiongenerator {\nreturn sub { shift() + shift() };\n}\n\nmy $addsub = addfunctiongenerator();\nmy $sum = $addsub->(4,5);                # $sum is 9 now.\n\nThe  anonymous  subroutine  returned  by addfunctiongenerator() isn't technically a closure\nbecause it refers to no lexicals outside its own scope. Using a closure gives you a  function\ntemplate with some customization slots left out to be filled later.\n\nContrast  this  with  the  following  makeadder()  function, in which the returned anonymous\nfunction contains a reference to a lexical  variable  outside  the  scope  of  that  function\nitself.  Such a reference requires that Perl return a proper closure, thus locking in for all\ntime the value that the lexical had when the function was created.\n\nsub makeadder {\nmy $addpiece = shift;\nreturn sub { shift() + $addpiece };\n}\n\nmy $f1 = makeadder(20);\nmy $f2 = makeadder(555);\n\nNow $f1->($n) is always 20 plus whatever $n you pass in, whereas $f2->($n) is always 555 plus\nwhatever $n you pass in. The $addpiece in the closure sticks around.\n\nClosures are often used for less esoteric purposes. For example, when you want to pass  in  a\nbit of code into a function:\n\nmy $line;\ntimeout( 30, sub { $line = <STDIN> } );\n\nIf  the  code  to execute had been passed in as a string, '$line = <STDIN>', there would have\nbeen no way for the hypothetical timeout() function to access the lexical variable $line back\nin its caller's scope.\n\nAnother use for a closure is to make a variable private to a named subroutine, e.g. a counter\nthat gets initialized at creation time of the sub and can only be modified  from  within  the\nsub.   This  is  sometimes  used  with a BEGIN block in package files to make sure a variable\ndoesn't get meddled with during the lifetime of the package:\n\nBEGIN {\nmy $id = 0;\nsub nextid { ++$id }\n}\n\nThis is discussed in more detail in perlsub; see the entry on Persistent Private Variables.\n"
                },
                {
                    "name": "What is variable suicide and how can I prevent it?",
                    "content": "This problem was fixed in perl 5.00405, so preventing it means  upgrading  your  version  of\nperl. ;)\n\nVariable suicide is when you (temporarily or permanently) lose the value of a variable. It is\ncaused  by  scoping  through  my()  and  local()  interacting with either closures or aliased\nforeach() iterator variables and subroutine arguments. It used to be  easy  to  inadvertently\nlose a variable's value this way, but now it's much harder. Take this code:\n\nmy $f = 'foo';\nsub T {\nwhile ($i++ < 3) { my $f = $f; $f .= \"bar\"; print $f, \"\\n\" }\n}\n\nT;\nprint \"Finally $f\\n\";\n\nIf  you  are  experiencing variable suicide, that \"my $f\" in the subroutine doesn't pick up a\nfresh copy of the $f whose value is 'foo'. The output shows that inside  the  subroutine  the\nvalue of $f leaks through when it shouldn't, as in this output:\n\nfoobar\nfoobarbar\nfoobarbarbar\nFinally foo\n\nThe  $f that has \"bar\" added to it three times should be a new $f \"my $f\" should create a new\nlexical variable each time through the loop.  The expected output is:\n\nfoobar\nfoobar\nfoobar\nFinally foo\n"
                },
                {
                    "name": "How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?",
                    "content": "You need to pass references to these objects. See \"Pass by Reference\"  in  perlsub  for  this\nparticular question, and perlref for information on references.\n\nPassing Variables and Functions\nRegular  variables  and  functions are quite easy to pass: just pass in a reference to an\nexisting or anonymous variable or function:\n\nfunc( \\$somescalar );\n\nfunc( \\@somearray  );\nfunc( [ 1 .. 10 ]   );\n\nfunc( \\%somehash   );\nfunc( { this => 10, that => 20 }   );\n\nfunc( \\&somefunc   );\nfunc( sub { $[0]  $[1] }   );\n\nPassing Filehandles\nAs of Perl 5.6, you can represent filehandles with scalar variables which  you  treat  as\nany other scalar.\n\nopen my $fh, $filename or die \"Cannot open $filename! $!\";\nfunc( $fh );\n\nsub func {\nmy $passedfh = shift;\n\nmy $line = <$passedfh>;\n}\n\nBefore  Perl 5.6, you had to use the *FH or \"\\*FH\" notations.  These are \"typeglobs\"--see\n\"Typeglobs and Filehandles\" in perldata and especially \"Pass by Reference\" in perlsub for\nmore information.\n\nPassing Regexes\nHere's an example of how to pass in a string and a regular expression  for  it  to  match\nagainst. You construct the pattern with the \"qr//\" operator:\n\nsub compare {\nmy ($val1, $regex) = @;\nmy $retval = $val1 =~ /$regex/;\nreturn $retval;\n}\n$match = compare(\"old McDonald\", qr/d.*D/i);\n\nPassing Methods\nTo pass an object method into a subroutine, you can do this:\n\ncallalot(10, $someobj, \"methname\")\nsub callalot {\nmy ($count, $widget, $trick) = @;\nfor (my $i = 0; $i < $count; $i++) {\n$widget->$trick();\n}\n}\n\nOr, you can use a closure to bundle up the object, its method call, and arguments:\n\nmy $whatnot = sub { $someobj->obfuscate(@args) };\nfunc($whatnot);\nsub func {\nmy $code = shift;\n&$code();\n}\n\nYou  could also investigate the can() method in the UNIVERSAL class (part of the standard\nperl distribution).\n"
                },
                {
                    "name": "How do I create a static variable?",
                    "content": "(contributed by brian d foy)\n\nIn Perl 5.10, declare the variable with \"state\". The \"state\" declaration creates the  lexical\nvariable that persists between calls to the subroutine:\n\nsub counter { state $count = 1; $count++ }\n\nYou  can  fake a static variable by using a lexical variable which goes out of scope. In this\nexample, you define the subroutine \"counter\", and it uses the lexical variable $count.  Since\nyou wrap this in a BEGIN block, $count is defined at compile-time, but also goes out of scope\nat the end of the BEGIN block. The BEGIN block also ensures that the subroutine and the value\nit  uses  is  defined  at  compile-time so the subroutine is ready to use just like any other\nsubroutine, and you can put this code in the same place as other subroutines in  the  program\ntext (i.e. at the end of the code, typically). The subroutine \"counter\" still has a reference\nto  the  data,  and  is  the  only  way  you  can access the value (and each time you do, you\nincrement the value).  The data in chunk of memory defined by $count is private to \"counter\".\n\nBEGIN {\nmy $count = 1;\nsub counter { $count++ }\n}\n\nmy $start = counter();\n\n.... # code that calls counter();\n\nmy $end = counter();\n\nIn the previous example, you created a function-private variable because  only  one  function\nremembered its reference. You could define multiple functions while the variable is in scope,\nand  each function can share the \"private\" variable. It's not really \"static\" because you can\naccess it outside the function while the lexical  variable  is  in  scope,  and  even  create\nreferences  to  it. In this example, \"incrementcount\" and \"returncount\" share the variable.\nOne function adds to the value and the other simply returns the value.  They can both  access\n$count, and since it has gone out of scope, there is no other way to access it.\n\nBEGIN {\nmy $count = 1;\nsub incrementcount { $count++ }\nsub returncount    { $count }\n}\n\nTo  declare  a  file-private  variable,  you  still use a lexical variable.  A file is also a\nscope, so a lexical variable defined in the file cannot be seen from any other file.\n\nSee \"Persistent Private Variables\" in  perlsub  for  more  information.   The  discussion  of\nclosures  in  perlref  may  help you even though we did not use anonymous subroutines in this\nanswer. See \"Persistent Private Variables\" in perlsub for details.\n"
                },
                {
                    "name": "What's the difference between dynamic and lexical (static) scoping? Between local() and my()?",
                    "content": "local($x) saves away the old value of the global variable $x and assigns a new value for  the\nduration  of  the subroutine which is visible in other functions called from that subroutine.\nThis is done at run-time, so  is  called  dynamic  scoping.  local()  always  affects  global\nvariables, also called package variables or dynamic variables.\n\nmy($x) creates a new variable that is only visible in the current subroutine. This is done at\ncompile-time,  so  it  is  called  lexical  or  static  scoping.  my() always affects private\nvariables, also called lexical variables or (improperly) static(ly scoped) variables.\n\nFor instance:\n\nsub visible {\nprint \"var has value $var\\n\";\n}\n\nsub dynamic {\nlocal $var = 'local';    # new temporary value for the still-global\nvisible();              #   variable called $var\n}\n\nsub lexical {\nmy $var = 'private';    # new private variable, $var\nvisible();              # (invisible outside of sub scope)\n}\n\n$var = 'global';\n\nvisible();              # prints global\ndynamic();              # prints local\nlexical();              # prints global\n\nNotice how at no point does the value \"private\" get printed. That's  because  $var  only  has\nthat  value  within  the  block  of  the lexical() function, and it is hidden from the called\nsubroutine.\n\nIn summary, local() doesn't make what you think of as private, local variables.  It  gives  a\nglobal  variable  a  temporary  value.  my()  is  what you're looking for if you want private\nvariables.\n\nSee \"Private Variables via my()\" in perlsub and \"Temporary Values via local()\" in perlsub for\nexcruciating details.\n"
                },
                {
                    "name": "How can I access a dynamic variable while a similarly named lexical is in scope?",
                    "content": "If you know your package, you can just mention it explicitly,  as  in  $SomePack::var.  Note\nthat  the  notation $::var is not the dynamic $var in the current package, but rather the one\nin the \"main\" package, as though you had written $main::var.\n\nuse vars '$var';\nlocal $var = \"global\";\nmy    $var = \"lexical\";\n\nprint \"lexical is $var\\n\";\nprint \"global  is $main::var\\n\";\n\nAlternatively you can use the compiler directive our() to bring a dynamic variable  into  the\ncurrent lexical scope.\n\nrequire 5.006; # our() did not exist before 5.6\nuse vars '$var';\n\nlocal $var = \"global\";\nmy $var    = \"lexical\";\n\nprint \"lexical is $var\\n\";\n\n{\nour $var;\nprint \"global  is $var\\n\";\n}\n"
                },
                {
                    "name": "What's the difference between deep and shallow binding?",
                    "content": "In  deep binding, lexical variables mentioned in anonymous subroutines are the same ones that\nwere in scope when the subroutine was  created.   In  shallow  binding,  they  are  whichever\nvariables  with  the  same  names  happen  to be in scope when the subroutine is called. Perl\nalways uses deep binding of lexical variables (i.e.,  those  created  with  my()).   However,\ndynamic  variables (aka global, local, or package variables) are effectively shallowly bound.\nConsider this just one more reason not to use them. See the answer to \"What's a closure?\".\n"
                },
                {
                    "name": "Why doesn't \"my($foo) = <$fh>;\" work right?",
                    "content": "my() and local() give list context to the right hand side of \"=\". The <$fh>  read  operation,\nlike  so  many of Perl's functions and operators, can tell which context it was called in and\nbehaves appropriately. In general, the  scalar()  function  can  help.   This  function  does\nnothing to the data itself (contrary to popular myth) but rather tells its argument to behave\nin  whatever its scalar fashion is.  If that function doesn't have a defined scalar behavior,\nthis of course doesn't help you (such as with sort()).\n\nTo enforce scalar context in  this  particular  case,  however,  you  need  merely  omit  the\nparentheses:\n\nlocal($foo) = <$fh>;        # WRONG\nlocal($foo) = scalar(<$fh>);   # ok\nlocal $foo  = <$fh>;        # right\n\nYou should probably be using lexical variables anyway, although the issue is the same here:\n\nmy($foo) = <$fh>;    # WRONG\nmy $foo  = <$fh>;    # right\n"
                },
                {
                    "name": "How do I redefine a builtin function, operator, or method?",
                    "content": "Why do you want to do that? :-)\n\nIf you want to override a predefined function, such as open(), then you'll have to import the\nnew definition from a different module. See \"Overriding Built-in Functions\" in perlsub.\n\nIf  you  want  to  overload a Perl operator, such as \"+\" or \"\", then you'll want to use the\n\"use overload\" pragma, documented in overload.\n\nIf you're talking about obscuring method calls in parent classes, see \"Overriding methods and\nmethod resolution\" in perlootut.\n"
                },
                {
                    "name": "What's the difference between calling a function as &foo and foo()?",
                    "content": "(contributed by brian d foy)\n\nCalling a subroutine as &foo with no trailing parentheses ignores the prototype of \"foo\"  and\npasses it the current value of the argument list, @. Here's an example; the \"bar\" subroutine\ncalls &foo, which prints its arguments list:\n\nsub foo { print \"Args in foo are: @\\n\"; }\n\nsub bar { &foo; }\n\nbar( \"a\", \"b\", \"c\" );\n\nWhen you call \"bar\" with arguments, you see that \"foo\" got the same @:\n\nArgs in foo are: a b c\n\nCalling the subroutine with trailing parentheses, with or without arguments, does not use the\ncurrent  @.  Changing  the  example  to  put parentheses after the call to \"foo\" changes the\nprogram:\n\nsub foo { print \"Args in foo are: @\\n\"; }\n\nsub bar { &foo(); }\n\nbar( \"a\", \"b\", \"c\" );\n\nNow the output shows that \"foo\" doesn't get the @ from its caller.\n\nArgs in foo are:\n\nHowever, using \"&\" in the call still overrides the prototype of \"foo\" if present:\n\nsub foo ($$$) { print \"Args infoo are: @\\n\"; }\n\nsub bar1 { &foo; }\nsub bar2 { &foo(); }\nsub bar3 { foo( $[0], $[1], $[2] ); }\n# sub bar4 { foo(); }\n# bar4 doesn't compile: \"Not enough arguments for main::foo at ...\"\n\nbar1( \"a\", \"b\", \"c\" );\n# Args in foo are: a b c\n\nbar2( \"a\", \"b\", \"c\" );\n# Args in foo are:\n\nbar3( \"a\", \"b\", \"c\" );\n# Args in foo are: a b c\n\nThe main use of the @ pass-through feature is to write subroutines whose main job it  is  to\ncall other subroutines for you. For further details, see perlsub.\n"
                },
                {
                    "name": "How do I create a switch or case statement?",
                    "content": "There  is  a  given/when  statement  in  Perl, but it is experimental and likely to change in\nfuture. See perlsyn for more details.\n\nThe general answer is to use a CPAN module such as Switch::Plain:\n\nuse Switch::Plain;\nsswitch($variableholdingastring) {\ncase 'first': { }\ncase 'second': { }\ndefault: { }\n}\n\nor for more complicated comparisons, \"if-elsif-else\":\n\nfor ($variabletotest) {\nif    (/pat1/)  { }     # do something\nelsif (/pat2/)  { }     # do something else\nelsif (/pat3/)  { }     # do something else\nelse            { }     # default\n}\n\nHere's a simple example of a switch based on pattern matching, lined up in a way to  make  it\nlook  more  like  a  switch  statement.  We'll do a multiway conditional based on the type of\nreference stored in $whatchamacallit:\n\nSWITCH: for (ref $whatchamacallit) {\n\n/^$/           && die \"not a reference\";\n\n/SCALAR/       && do {\nprintscalar($$ref);\nlast SWITCH;\n};\n\n/ARRAY/        && do {\nprintarray(@$ref);\nlast SWITCH;\n};\n\n/HASH/        && do {\nprinthash(%$ref);\nlast SWITCH;\n};\n\n/CODE/        && do {\nwarn \"can't print function ref\";\nlast SWITCH;\n};\n\n# DEFAULT\n\nwarn \"User defined type skipped\";\n\n}\n\nSee perlsyn for other examples in this style.\n\nSometimes you should change the positions of the constant and  the  variable.   For  example,\nlet's  say you wanted to test which of many answers you were given, but in a case-insensitive\nway that also allows abbreviations.  You can use the following technique if the  strings  all\nstart  with  different  characters  or  if  you want to arrange the matches so that one takes\nprecedence over another, as \"SEND\" has precedence over \"STOP\" here:\n\nchomp($answer = <>);\nif    (\"SEND\"  =~ /^\\Q$answer/i) { print \"Action is send\\n\"  }\nelsif (\"STOP\"  =~ /^\\Q$answer/i) { print \"Action is stop\\n\"  }\nelsif (\"ABORT\" =~ /^\\Q$answer/i) { print \"Action is abort\\n\" }\nelsif (\"LIST\"  =~ /^\\Q$answer/i) { print \"Action is list\\n\"  }\nelsif (\"EDIT\"  =~ /^\\Q$answer/i) { print \"Action is edit\\n\"  }\n\nA totally different approach is to create a hash of function references.\n\nmy %commands = (\n\"happy\" => \\&joy,\n\"sad\",  => \\&sullen,\n\"done\"  => sub { die \"See ya!\" },\n\"mad\"   => \\&angry,\n);\n\nprint \"How are you? \";\nchomp($string = <STDIN>);\nif ($commands{$string}) {\n$commands{$string}->();\n} else {\nprint \"No such command: $string\\n\";\n}\n\nStarting from Perl 5.8, a source filter module, \"Switch\", can also be used to get switch  and\ncase. Its use is now discouraged, because it's not fully compatible with the native switch of\nPerl  5.10,  and  because,  as it's implemented as a source filter, it doesn't always work as\nintended when complex syntax is involved.\n"
                },
                {
                    "name": "How can I catch accesses to undefined variables, functions, or methods?",
                    "content": "The AUTOLOAD method, discussed  in  \"Autoloading\"  in  perlsub  lets  you  capture  calls  to\nundefined functions and methods.\n\nWhen  it  comes to undefined variables that would trigger a warning under \"use warnings\", you\ncan promote the warning to an error.\n\nuse warnings FATAL => qw(uninitialized);\n"
                },
                {
                    "name": "Why can't a method included in this same file be found?",
                    "content": "Some possible reasons: your inheritance is getting confused,  you've  misspelled  the  method\nname,  or  the  object is of the wrong type. Check out perlootut for details about any of the\nabove cases. You may also use \"print ref($object)\" to find out the class $object was  blessed\ninto.\n\nAnother  possible  reason  for  problems  is that you've used the indirect object syntax (eg,\n\"find Guru \"Samy\"\") on a class name before Perl has seen that such  a  package  exists.  It's\nwisest  to make sure your packages are all defined before you start using them, which will be\ntaken care of if you use the \"use\" statement instead of \"require\". If not, make sure  to  use\narrow notation (eg., \"Guru->find(\"Samy\")\") instead. Object notation is explained in perlobj.\n\nMake  sure  to  read  about creating modules in perlmod and the perils of indirect objects in\n\"Method Invocation\" in perlobj.\n"
                },
                {
                    "name": "How can I find out my current or calling package?",
                    "content": "(contributed by brian d foy)\n\nTo find the package  you  are  currently  in,  use  the  special  literal  \"PACKAGE\",  as\ndocumented  in  perldata.  You  can  only use the special literals as separate tokens, so you\ncan't interpolate them into strings like you can with variables:\n\nmy $currentpackage = PACKAGE;\nprint \"I am in package $currentpackage\\n\";\n\nIf you want to find the package calling your code, perhaps to give better diagnostics as Carp\ndoes, use the \"caller\" built-in:\n\nsub foo {\nmy @args = ...;\nmy( $package, $filename, $line ) = caller;\n\nprint \"I was called from package $package\\n\";\n);\n\nBy default, your program starts in package \"main\", so you will always be in some package.\n\nThis is different from finding out the package an object is blessed into, which might not  be\nthe  current package. For that, use \"blessed\" from Scalar::Util, part of the Standard Library\nsince Perl 5.8:\n\nuse Scalar::Util qw(blessed);\nmy $objectpackage = blessed( $object );\n\nMost of the time, you shouldn't care what package an object is blessed into, however, as long\nas it claims to inherit from that class:\n\nmy $isrightclass = eval { $object->isa( $package ) }; # true or false\n\nAnd, with Perl 5.10 and later, you don't have to check for  an  inheritance  to  see  if  the\nobject can handle a role. For that, you can use \"DOES\", which comes from \"UNIVERSAL\":\n\nmy $classdoesit = eval { $object->DOES( $role ) }; # true or false\n\nYou can safely replace \"isa\" with \"DOES\" (although the converse is not true).\n"
                },
                {
                    "name": "How can I comment out a large block of Perl code?",
                    "content": "(contributed by brian d foy)\n\nThe  quick-and-dirty way to comment out more than one line of Perl is to surround those lines\nwith Pod directives. You have to put these directives  at  the  beginning  of  the  line  and\nsomewhere where Perl expects a new statement (so not in the middle of statements like the \"#\"\ncomments). You end the comment with \"=cut\", ending the Pod section:\n\n=pod\n\nmy $object = NotGonnaHappen->new();\n\nignoredsub();\n\n$wontbeassigned = 37;\n\n=cut\n\nThe quick-and-dirty method only works well when you don't plan to leave the commented code in\nthe  source.  If  a Pod parser comes along, your multiline comment is going to show up in the\nPod translation.  A better way hides it from Pod parsers as well.\n\nThe \"=begin\" directive can mark a section for  a  particular  purpose.   If  the  Pod  parser\ndoesn't  want  to  handle  it, it just ignores it. Label the comments with \"comment\". End the\ncomment using \"=end\" with the same label. You still need the \"=cut\" to go back to  Perl  code\nfrom the Pod comment:\n\n=begin comment\n\nmy $object = NotGonnaHappen->new();\n\nignoredsub();\n\n$wontbeassigned = 37;\n\n=end comment\n\n=cut\n\nFor more information on Pod, check out perlpod and perlpodspec.\n"
                },
                {
                    "name": "How do I clear a package?",
                    "content": "Use this code, provided by Mark-Jason Dominus:\n\nsub scrubpackage {\nno strict 'refs';\nmy $pack = shift;\ndie \"Shouldn't delete main package\"\nif $pack eq \"\" || $pack eq \"main\";\nmy $stash = *{$pack . '::'}{HASH};\nmy $name;\nforeach $name (keys %$stash) {\nmy $fullname = $pack . '::' . $name;\n# Get rid of everything with that name.\nundef $$fullname;\nundef @$fullname;\nundef %$fullname;\nundef &$fullname;\nundef *$fullname;\n}\n}\n\nOr,  if  you're using a recent release of Perl, you can just use the Symbol::deletepackage()\nfunction instead.\n"
                },
                {
                    "name": "How can I use a variable as a variable name?",
                    "content": "Beginners often think they want to have a variable contain the name of a variable.\n\n$fred    = 23;\n$varname = \"fred\";\n++$$varname;         # $fred now 24\n\nThis works sometimes, but it is a very bad idea for two reasons.\n\nThe first reason is that this technique only works on global variables. That  means  that  if\n$fred is a lexical variable created with my() in the above example, the code wouldn't work at\nall: you'd accidentally access the global and skip right over the private lexical altogether.\nGlobal variables are bad because they can easily collide accidentally and in general make for\nnon-scalable and confusing code.\n\nSymbolic  references  are  forbidden  under  the  \"use  strict\"  pragma.   They  are not true\nreferences and consequently are not reference-counted or garbage-collected.\n\nThe other reason why using a variable to hold the name of another variable is a bad  idea  is\nthat  the  question  often  stems  from  a  lack  of  understanding  of Perl data structures,\nparticularly hashes. By using symbolic references, you are just using the  package's  symbol-\ntable  hash  (like  %main::)  instead of a user-defined hash. The solution is to use your own\nhash or a real reference instead.\n\n$USERVARS{\"fred\"} = 23;\nmy $varname = \"fred\";\n$USERVARS{$varname}++;  # not $$varname++\n\nThere we're using the %USERVARS hash instead of symbolic references.  Sometimes  this  comes\nup  in  reading  strings from the user with variable references and wanting to expand them to\nthe values of your perl program's variables. This is also a bad idea because it conflates the\nprogram-addressable namespace and the user-addressable one. Instead of reading a  string  and\nexpanding it to the actual contents of your program's own variables:\n\n$str = 'this has a $fred and $barney in it';\n$str =~ s/(\\$\\w+)/$1/eeg;          # need double eval\n\nit  would  be  better  to  keep  a  hash  around like %USERVARS and have variable references\nactually refer to entries in that hash:\n\n$str =~ s/\\$(\\w+)/$USERVARS{$1}/g;   # no /e here at all\n\nThat's faster, cleaner, and safer than the previous approach. Of course, you  don't  need  to\nuse  a  dollar  sign. You could use your own scheme to make it less confusing, like bracketed\npercent symbols, etc.\n\n$str = 'this has a %fred% and %barney% in it';\n$str =~ s/%(\\w+)%/$USERVARS{$1}/g;   # no /e here at all\n\nAnother reason that folks sometimes think they want a variable  to  contain  the  name  of  a\nvariable  is  that  they  don't  know  how  to build proper data structures using hashes. For\nexample, let's say they wanted two hashes in their program: %fred and %barney, and that  they\nwanted to use another scalar variable to refer to those by name.\n\n$name = \"fred\";\n$$name{WIFE} = \"wilma\";     # set %fred\n\n$name = \"barney\";\n$$name{WIFE} = \"betty\";    # set %barney\n\nThis  is still a symbolic reference, and is still saddled with the problems enumerated above.\nIt would be far better to write:\n\n$folks{\"fred\"}{WIFE}   = \"wilma\";\n$folks{\"barney\"}{WIFE} = \"betty\";\n\nAnd just use a multilevel hash to start with.\n\nThe only times that you absolutely must use symbolic references  are  when  you  really  must\nrefer  to  the  symbol  table.  This may be because it's something that one can't take a real\nreference to, such as a format name.  Doing so may also be important for method calls,  since\nthese always go through the symbol table for resolution.\n\nIn  those  cases,  you would turn off \"strict 'refs'\" temporarily so you can play around with\nthe symbol table. For example:\n\n@colors = qw(red blue green yellow orange purple violet);\nfor my $name (@colors) {\nno strict 'refs';  # renege for the block\n*$name = sub { \"<FONT COLOR='$name'>@</FONT>\" };\n}\n\nAll those functions (red(), blue(), green(), etc.) appear to be separate, but the  real  code\nin the closure actually was compiled only once.\n\nSo,  sometimes  you  might  want  to  use  symbolic references to manipulate the symbol table\ndirectly. This doesn't matter for formats, handles, and subroutines, because they are  always\nglobal--you can't use my() on them.  For scalars, arrays, and hashes, though--and usually for\nsubroutines-- you probably only want to use hard references.\n"
                },
                {
                    "name": "What does \"bad interpreter\" mean?",
                    "content": "(contributed by brian d foy)\n\nThe  \"bad  interpreter\"  message  comes from the shell, not perl. The actual message may vary\ndepending on your platform, shell, and locale settings.\n\nIf you see \"bad interpreter - no such file or directory\", the first line in your perl  script\n(the \"shebang\" line) does not contain the right path to perl (or any other program capable of\nrunning  scripts).   Sometimes  this  happens  when  you  move the script from one machine to\nanother  and  each   machine   has   a   different   path   to   perl--/usr/bin/perl   versus\n/usr/local/bin/perl  for instance. It may also indicate that the source machine has CRLF line\nterminators  and  the  destination  machine  has  LF  only:   the   shell   tries   to   find\n/usr/bin/perl<CR>, but can't.\n\nIf you see \"bad interpreter: Permission denied\", you need to make your script executable.\n\nIn either case, you should still be able to run the scripts with perl explicitly:\n\n% perl script.pl\n\nIf  you  get  a message like \"perl: command not found\", perl is not in your PATH, which might\nalso mean that the location of perl is not where you expect it so you  need  to  adjust  your\nshebang line.\n"
                },
                {
                    "name": "Do I need to recompile XS modules when there is a change in the C library?",
                    "content": "(contributed by Alex Beamish)\n\nIf  the  new  version of the C library is ABI-compatible (that's Application Binary Interface\ncompatible) with the version you're upgrading from, and if the shared library version  didn't\nchange, no re-compilation should be necessary.\n"
                }
            ]
        },
        "AUTHOR AND COPYRIGHT": {
            "content": "Copyright  (c) 1997-2013 Tom Christiansen, Nathan Torkington, and other authors as noted. All\nrights reserved.\n\nThis documentation is free; you can redistribute it and/or modify it under the same terms  as\nPerl itself.\n\nIrrespective  of  its distribution, all code examples in this file are hereby placed into the\npublic domain. You are permitted and encouraged to use this code in your own programs for fun\nor for profit as you see fit. A simple comment in the code giving credit would  be  courteous\nbut is not required.\n\nperl v5.38.2                                 2026-08-18                                  PERLFAQ7(1)",
            "subsections": []
        }
    },
    "summary": "perlfaq7 - General Perl Language Issues",
    "flags": [],
    "examples": [],
    "see_also": []
}