{
    "content": [
        {
            "type": "text",
            "text": "# PERLFAQ8 (man)\n\n## NAME\n\nperlfaq8 - System Interaction\n\n## DESCRIPTION\n\nThis section of the Perl FAQ covers questions involving operating system interaction. Topics\ninclude interprocess communication (IPC), control over the user-interface (keyboard, screen\nand pointing devices), and most anything else not related to data manipulation.\n\n## Sections\n\n- **NAME**\n- **VERSION**\n- **DESCRIPTION** (53 subsections)\n- **AUTHOR AND COPYRIGHT**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "PERLFAQ8",
        "section": "",
        "mode": "man",
        "summary": "perlfaq8 - System Interaction",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "VERSION",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 8,
                "subsections": [
                    {
                        "name": "How do I find out which operating system I'm running under?",
                        "lines": 3
                    },
                    {
                        "name": "How come exec() doesn't return?",
                        "lines": 8
                    },
                    {
                        "name": "How do I do fancy stuff with the keyboard/screen/mouse?",
                        "lines": 24
                    },
                    {
                        "name": "How do I print something out in color?",
                        "lines": 14
                    },
                    {
                        "name": "How do I read just one key without waiting for a return key?",
                        "lines": 74
                    },
                    {
                        "name": "How do I check whether input is ready on the keyboard?",
                        "lines": 15
                    },
                    {
                        "name": "How do I clear the screen?",
                        "lines": 40
                    },
                    {
                        "name": "How do I get the screen size?",
                        "lines": 19
                    },
                    {
                        "name": "How do I ask the user for a password?",
                        "lines": 15
                    },
                    {
                        "name": "How do I read and write the serial port?",
                        "lines": 78
                    },
                    {
                        "name": "How do I decode encrypted password files?",
                        "lines": 12
                    },
                    {
                        "name": "How do I start a process in the background?",
                        "lines": 53
                    },
                    {
                        "name": "How do I trap control characters/signals?",
                        "lines": 27
                    },
                    {
                        "name": "How do I modify the shadow password file on a Unix system?",
                        "lines": 6
                    },
                    {
                        "name": "How do I set the time and date?",
                        "lines": 12
                    },
                    {
                        "name": "How can I sleep() or alarm() for under a second?",
                        "lines": 5
                    },
                    {
                        "name": "How can I measure time under a second?",
                        "lines": 7
                    },
                    {
                        "name": "How can I do an atexit() or setjmp()/longjmp()? (Exception handling)",
                        "lines": 26
                    },
                    {
                        "name": "Why doesn't my sockets program work under System V (Solaris)? What does the error message",
                        "lines": 1
                    },
                    {
                        "name": "\"Protocol not supported\" mean?",
                        "lines": 7
                    },
                    {
                        "name": "How can I call my system's unique C functions from Perl?",
                        "lines": 10
                    },
                    {
                        "name": "Where do I get the include files to do ioctl() or syscall()?",
                        "lines": 19
                    },
                    {
                        "name": "Why do setuid perl scripts complain about kernel problems?",
                        "lines": 3
                    },
                    {
                        "name": "How can I open a pipe both to and from a command?",
                        "lines": 9
                    },
                    {
                        "name": "Why can't I get the output of a command with system()?",
                        "lines": 8
                    },
                    {
                        "name": "How can I capture STDERR from an external command?",
                        "lines": 140
                    },
                    {
                        "name": "Why doesn't open() return an error when a pipe open fails?",
                        "lines": 10
                    },
                    {
                        "name": "What's wrong with using backticks in a void context?",
                        "lines": 27
                    },
                    {
                        "name": "How can I call backticks without shell processing?",
                        "lines": 31
                    },
                    {
                        "name": "Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?",
                        "lines": 17
                    },
                    {
                        "name": "How can I convert my shell script to perl?",
                        "lines": 6
                    },
                    {
                        "name": "Can I use perl to run a telnet or ftp session?",
                        "lines": 20
                    },
                    {
                        "name": "How can I write expect in Perl?",
                        "lines": 5
                    },
                    {
                        "name": "Is there a way to hide perl's command line from programs such as \"ps\"?",
                        "lines": 10
                    },
                    {
                        "name": "I {changed directory, modified my environment} in a perl script. How come the change disappeared",
                        "lines": 1
                    },
                    {
                        "name": "when I exited the script? How do I get my changes to be visible?",
                        "lines": 7
                    },
                    {
                        "name": "How do I close a process's filehandle without waiting for it to complete?",
                        "lines": 4
                    },
                    {
                        "name": "How do I fork a daemon process?",
                        "lines": 19
                    },
                    {
                        "name": "How do I find out if I'm running interactively or not?",
                        "lines": 34
                    },
                    {
                        "name": "How do I timeout a slow event?",
                        "lines": 7
                    },
                    {
                        "name": "How do I set CPU limits?",
                        "lines": 15
                    },
                    {
                        "name": "How do I avoid zombies on a Unix system?",
                        "lines": 4
                    },
                    {
                        "name": "How do I use an SQL database?",
                        "lines": 9
                    },
                    {
                        "name": "How do I make a system() exit on control-C?",
                        "lines": 7
                    },
                    {
                        "name": "How do I open a file without blocking?",
                        "lines": 8
                    },
                    {
                        "name": "How do I tell the difference between errors from the shell and perl?",
                        "lines": 60
                    },
                    {
                        "name": "How do I install a module from CPAN?",
                        "lines": 36
                    },
                    {
                        "name": "What's the difference between require and use?",
                        "lines": 29
                    },
                    {
                        "name": "How do I keep my own module/library directory?",
                        "lines": 40
                    },
                    {
                        "name": "How do I add the directory my program lives in to the module/library search path?",
                        "lines": 44
                    },
                    {
                        "name": "How do I add a directory to my include path (@INC) at runtime?",
                        "lines": 22
                    },
                    {
                        "name": "Where are modules installed?",
                        "lines": 18
                    },
                    {
                        "name": "What is socket.ph and where do I get it?",
                        "lines": 4
                    }
                ]
            },
            {
                "name": "AUTHOR AND COPYRIGHT",
                "lines": 14,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "perlfaq8 - System Interaction\n",
                "subsections": []
            },
            "VERSION": {
                "content": "version 5.20210411\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "This section of the Perl FAQ covers questions involving operating system interaction. Topics\ninclude interprocess communication (IPC), control over the user-interface (keyboard, screen\nand pointing devices), and most anything else not related to data manipulation.\n\nRead the FAQs and documentation specific to the port of perl to your operating system (eg,\nperlvms, perlplan9, ...). These should contain more detailed information on the vagaries of\nyour perl.\n",
                "subsections": [
                    {
                        "name": "How do I find out which operating system I'm running under?",
                        "content": "The $^O variable ($OSNAME if you use \"English\") contains an indication of the name of the\noperating system (not its release number) that your perl binary was built for.\n"
                    },
                    {
                        "name": "How come exec() doesn't return?",
                        "content": "(contributed by brian d foy)\n\nThe \"exec\" function's job is to turn your process into another command and never to return.\nIf that's not what you want to do, don't use \"exec\". :)\n\nIf you want to run an external command and still keep your Perl process going, look at a\npiped \"open\", \"fork\", or \"system\".\n"
                    },
                    {
                        "name": "How do I do fancy stuff with the keyboard/screen/mouse?",
                        "content": "How you access/control keyboards, screens, and pointing devices (\"mice\") is system-dependent.\nTry the following modules:\n\nKeyboard\nTerm::Cap               Standard perl distribution\nTerm::ReadKey           CPAN\nTerm::ReadLine::Gnu     CPAN\nTerm::ReadLine::Perl    CPAN\nTerm::Screen            CPAN\n\nScreen\nTerm::Cap               Standard perl distribution\nCurses                  CPAN\nTerm::ANSIColor         CPAN\n\nMouse\nTk                      CPAN\nWx                      CPAN\nGtk2                    CPAN\nQt4                     kdebindings4 package\n\nSome of these specific cases are shown as examples in other answers in this section of the\nperlfaq.\n"
                    },
                    {
                        "name": "How do I print something out in color?",
                        "content": "In general, you don't, because you don't know whether the recipient has a color-aware display\ndevice. If you know that they have an ANSI terminal that understands color, you can use the\nTerm::ANSIColor module from CPAN:\n\nuse Term::ANSIColor;\nprint color(\"red\"), \"Stop!\\n\", color(\"reset\");\nprint color(\"green\"), \"Go!\\n\", color(\"reset\");\n\nOr like this:\n\nuse Term::ANSIColor qw(:constants);\nprint RED, \"Stop!\\n\", RESET;\nprint GREEN, \"Go!\\n\", RESET;\n"
                    },
                    {
                        "name": "How do I read just one key without waiting for a return key?",
                        "content": "Controlling input buffering is a remarkably system-dependent matter.  On many systems, you\ncan just use the stty command as shown in \"getc\" in perlfunc, but as you see, that's already\ngetting you into portability snags.\n\nopen(TTY, \"+</dev/tty\") or die \"no tty: $!\";\nsystem \"stty  cbreak </dev/tty >/dev/tty 2>&1\";\n$key = getc(TTY);        # perhaps this works\n# OR ELSE\nsysread(TTY, $key, 1);    # probably this does\nsystem \"stty -cbreak </dev/tty >/dev/tty 2>&1\";\n\nThe Term::ReadKey module from CPAN offers an easy-to-use interface that should be more\nefficient than shelling out to stty for each key.  It even includes limited support for\nWindows.\n\nuse Term::ReadKey;\nReadMode('cbreak');\n$key = ReadKey(0);\nReadMode('normal');\n\nHowever, using the code requires that you have a working C compiler and can use it to build\nand install a CPAN module. Here's a solution using the standard POSIX module, which is\nalready on your system (assuming your system supports POSIX).\n\nuse HotKey;\n$key = readkey();\n\nAnd here's the \"HotKey\" module, which hides the somewhat mystifying calls to manipulate the\nPOSIX termios structures.\n\n# HotKey.pm\npackage HotKey;\n\nuse strict;\nuse warnings;\n\nuse parent 'Exporter';\nour @EXPORT = qw(cbreak cooked readkey);\n\nuse POSIX qw(:termiosh);\nmy ($term, $oterm, $echo, $noecho, $fdstdin);\n\n$fdstdin = fileno(STDIN);\n$term     = POSIX::Termios->new();\n$term->getattr($fdstdin);\n$oterm     = $term->getlflag();\n\n$echo     = ECHO | ECHOK | ICANON;\n$noecho   = $oterm & ~$echo;\n\nsub cbreak {\n$term->setlflag($noecho);  # ok, so i don't want echo either\n$term->setcc(VTIME, 1);\n$term->setattr($fdstdin, TCSANOW);\n}\n\nsub cooked {\n$term->setlflag($oterm);\n$term->setcc(VTIME, 0);\n$term->setattr($fdstdin, TCSANOW);\n}\n\nsub readkey {\nmy $key = '';\ncbreak();\nsysread(STDIN, $key, 1);\ncooked();\nreturn $key;\n}\n\nEND { cooked() }\n\n1;\n"
                    },
                    {
                        "name": "How do I check whether input is ready on the keyboard?",
                        "content": "The easiest way to do this is to read a key in nonblocking mode with the Term::ReadKey module\nfrom CPAN, passing it an argument of -1 to indicate not to block:\n\nuse Term::ReadKey;\n\nReadMode('cbreak');\n\nif (defined (my $char = ReadKey(-1)) ) {\n# input was waiting and it was $char\n} else {\n# no input was waiting\n}\n\nReadMode('normal');                  # restore normal tty settings\n"
                    },
                    {
                        "name": "How do I clear the screen?",
                        "content": "(contributed by brian d foy)\n\nTo clear the screen, you just have to print the special sequence that tells the terminal to\nclear the screen. Once you have that sequence, output it when you want to clear the screen.\n\nYou can use the Term::ANSIScreen module to get the special sequence. Import the \"cls\"\nfunction (or the \":screen\" tag):\n\nuse Term::ANSIScreen qw(cls);\nmy $clearscreen = cls();\n\nprint $clearscreen;\n\nThe Term::Cap module can also get the special sequence if you want to deal with the low-level\ndetails of terminal control. The \"Tputs\" method returns the string for the given capability:\n\nuse Term::Cap;\n\nmy $terminal = Term::Cap->Tgetent( { OSPEED => 9600 } );\nmy $clearscreen = $terminal->Tputs('cl');\n\nprint $clearscreen;\n\nOn Windows, you can use the Win32::Console module. After creating an object for the output\nfilehandle you want to affect, call the \"Cls\" method:\n\nWin32::Console;\n\nmy $OUT = Win32::Console->new(STDOUTPUTHANDLE);\nmy $clearstring = $OUT->Cls;\n\nprint $clearscreen;\n\nIf you have a command-line program that does the job, you can call it in backticks to capture\nwhatever it outputs so you can use it later:\n\nmy $clearstring = `clear`;\n\nprint $clearstring;\n"
                    },
                    {
                        "name": "How do I get the screen size?",
                        "content": "If you have Term::ReadKey module installed from CPAN, you can use it to fetch the width and\nheight in characters and in pixels:\n\nuse Term::ReadKey;\nmy ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();\n\nThis is more portable than the raw \"ioctl\", but not as illustrative:\n\nrequire './sys/ioctl.ph';\ndie \"no TIOCGWINSZ \" unless defined &TIOCGWINSZ;\nopen(my $ttyfh, \"+</dev/tty\")                     or die \"No tty: $!\";\nunless (ioctl($ttyfh, &TIOCGWINSZ, $winsize='')) {\ndie sprintf \"$0: ioctl TIOCGWINSZ (%08x: $!)\\n\", &TIOCGWINSZ;\n}\nmy ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);\nprint \"(row,col) = ($row,$col)\";\nprint \"  (xpixel,ypixel) = ($xpixel,$ypixel)\" if $xpixel || $ypixel;\nprint \"\\n\";\n"
                    },
                    {
                        "name": "How do I ask the user for a password?",
                        "content": "(This question has nothing to do with the web. See a different FAQ for that.)\n\nThere's an example of this in \"crypt\" in perlfunc. First, you put the terminal into \"no echo\"\nmode, then just read the password normally.  You may do this with an old-style \"ioctl()\"\nfunction, POSIX terminal control (see POSIX or its documentation the Camel Book), or a call\nto the stty program, with varying degrees of portability.\n\nYou can also do this for most systems using the Term::ReadKey module from CPAN, which is\neasier to use and in theory more portable.\n\nuse Term::ReadKey;\n\nReadMode('noecho');\nmy $password = ReadLine(0);\n"
                    },
                    {
                        "name": "How do I read and write the serial port?",
                        "content": "This depends on which operating system your program is running on. In the case of Unix, the\nserial ports will be accessible through files in \"/dev\"; on other systems, device names will\ndoubtless differ.  Several problem areas common to all device interaction are the following:\n\nlockfiles\nYour system may use lockfiles to control multiple access. Make sure you follow the\ncorrect protocol. Unpredictable behavior can result from multiple processes reading from\none device.\n\nopen mode\nIf you expect to use both read and write operations on the device, you'll have to open it\nfor update (see \"open\" in perlfunc for details). You may wish to open it without running\nthe risk of blocking by using \"sysopen()\" and \"ORDWR|ONDELAY|ONOCTTY\" from the Fcntl\nmodule (part of the standard perl distribution). See \"sysopen\" in perlfunc for more on\nthis approach.\n\nend of line\nSome devices will be expecting a \"\\r\" at the end of each line rather than a \"\\n\". In some\nports of perl, \"\\r\" and \"\\n\" are different from their usual (Unix) ASCII values of \"\\015\"\nand \"\\012\". You may have to give the numeric values you want directly, using octal\n(\"\\015\"), hex (\"0x0D\"), or as a control-character specification (\"\\cM\").\n\nprint DEV \"atv1\\012\";    # wrong, for some devices\nprint DEV \"atv1\\015\";    # right, for some devices\n\nEven though with normal text files a \"\\n\" will do the trick, there is still no unified\nscheme for terminating a line that is portable between Unix, DOS/Win, and Macintosh,\nexcept to terminate ALL line ends with \"\\015\\012\", and strip what you don't need from the\noutput.  This applies especially to socket I/O and autoflushing, discussed next.\n\nflushing output\nIf you expect characters to get to your device when you \"print()\" them, you'll want to\nautoflush that filehandle. You can use \"select()\" and the $| variable to control\nautoflushing (see \"$|\" in perlvar and \"select\" in perlfunc, or perlfaq5, \"How do I\nflush/unbuffer an output filehandle? Why must I do this?\"):\n\nmy $oldhandle = select($devfh);\n$| = 1;\nselect($oldhandle);\n\nYou'll also see code that does this without a temporary variable, as in\n\nselect((select($debhandle), $| = 1)[0]);\n\nOr if you don't mind pulling in a few thousand lines of code just because you're afraid\nof a little $| variable:\n\nuse IO::Handle;\n$devfh->autoflush(1);\n\nAs mentioned in the previous item, this still doesn't work when using socket I/O between\nUnix and Macintosh. You'll need to hard code your line terminators, in that case.\n\nnon-blocking input\nIf you are doing a blocking \"read()\" or \"sysread()\", you'll have to arrange for an alarm\nhandler to provide a timeout (see \"alarm\" in perlfunc). If you have a non-blocking open,\nyou'll likely have a non-blocking read, which means you may have to use a 4-arg\n\"select()\" to determine whether I/O is ready on that device (see \"select\" in perlfunc.\n\nWhile trying to read from his caller-id box, the notorious Jamie Zawinski\n\"<jwz@netscape.com>\", after much gnashing of teeth and fighting with \"sysread\", \"sysopen\",\nPOSIX's \"tcgetattr\" business, and various other functions that go bump in the night, finally\ncame up with this:\n\nsub openmodem {\nuse IPC::Open2;\nmy $stty = `/bin/stty -g`;\nopen2( \\*MODEMIN, \\*MODEMOUT, \"cu -l$modemdevice -s2400 2>&1\");\n# starting cu hoses /dev/tty's stty settings, even when it has\n# been opened on a pipe...\nsystem(\"/bin/stty $stty\");\n$ = <MODEMIN>;\nchomp;\nif ( !m/^Connected/ ) {\nprint STDERR \"$0: cu printed `$' instead of `Connected'\\n\";\n}\n}\n"
                    },
                    {
                        "name": "How do I decode encrypted password files?",
                        "content": "You spend lots and lots of money on dedicated hardware, but this is bound to get you talked\nabout.\n\nSeriously, you can't if they are Unix password files--the Unix password system employs one-\nway encryption. It's more like hashing than encryption. The best you can do is check whether\nsomething else hashes to the same string. You can't turn a hash back into the original\nstring. Programs like Crack can forcibly (and intelligently) try to guess passwords, but\ndon't (can't) guarantee quick success.\n\nIf you're worried about users selecting bad passwords, you should proactively check when they\ntry to change their password (by modifying passwd(1), for example).\n"
                    },
                    {
                        "name": "How do I start a process in the background?",
                        "content": "(contributed by brian d foy)\n\nThere's not a single way to run code in the background so you don't have to wait for it to\nfinish before your program moves on to other tasks. Process management depends on your\nparticular operating system, and many of the techniques are covered in perlipc.\n\nSeveral CPAN modules may be able to help, including IPC::Open2 or IPC::Open3, IPC::Run,\nParallel::Jobs, Parallel::ForkManager, POE, Proc::Background, and Win32::Process. There are\nmany other modules you might use, so check those namespaces for other options too.\n\nIf you are on a Unix-like system, you might be able to get away with a system call where you\nput an \"&\" on the end of the command:\n\nsystem(\"cmd &\")\n\nYou can also try using \"fork\", as described in perlfunc (although this is the same thing that\nmany of the modules will do for you).\n\nSTDIN, STDOUT, and STDERR are shared\nBoth the main process and the backgrounded one (the \"child\" process) share the same\nSTDIN, STDOUT and STDERR filehandles. If both try to access them at once, strange things\ncan happen. You may want to close or reopen these for the child. You can get around this\nwith \"open\"ing a pipe (see \"open\" in perlfunc) but on some systems this means that the\nchild process cannot outlive the parent.\n\nSignals\nYou'll have to catch the SIGCHLD signal, and possibly SIGPIPE too.  SIGCHLD is sent when\nthe backgrounded process finishes. SIGPIPE is sent when you write to a filehandle whose\nchild process has closed (an untrapped SIGPIPE can cause your program to silently die).\nThis is not an issue with \"system(\"cmd&\")\".\n\nZombies\nYou have to be prepared to \"reap\" the child process when it finishes.\n\n$SIG{CHLD} = sub { wait };\n\n$SIG{CHLD} = 'IGNORE';\n\nYou can also use a double fork. You immediately \"wait()\" for your first child, and the\ninit daemon will \"wait()\" for your grandchild once it exits.\n\nunless ($pid = fork) {\nunless (fork) {\nexec \"what you really wanna do\";\ndie \"exec failed!\";\n}\nexit 0;\n}\nwaitpid($pid, 0);\n\nSee \"Signals\" in perlipc for other examples of code to do this.  Zombies are not an issue\nwith \"system(\"prog &\")\".\n"
                    },
                    {
                        "name": "How do I trap control characters/signals?",
                        "content": "You don't actually \"trap\" a control character. Instead, that character generates a signal\nwhich is sent to your terminal's currently foregrounded process group, which you then trap in\nyour process.  Signals are documented in \"Signals\" in perlipc and the section on \"Signals\" in\nthe Camel.\n\nYou can set the values of the %SIG hash to be the functions you want to handle the signal.\nAfter perl catches the signal, it looks in %SIG for a key with the same name as the signal,\nthen calls the subroutine value for that key.\n\n# as an anonymous subroutine\n\n$SIG{INT} = sub { syswrite(STDERR, \"ouch\\n\", 5 ) };\n\n# or a reference to a function\n\n$SIG{INT} = \\&ouch;\n\n# or the name of the function as a string\n\n$SIG{INT} = \"ouch\";\n\nPerl versions before 5.8 had in its C source code signal handlers which would catch the\nsignal and possibly run a Perl function that you had set in %SIG. This violated the rules of\nsignal handling at that level causing perl to dump core. Since version 5.8.0, perl looks at\n%SIG after the signal has been caught, rather than while it is being caught.  Previous\nversions of this answer were incorrect.\n"
                    },
                    {
                        "name": "How do I modify the shadow password file on a Unix system?",
                        "content": "If perl was installed correctly and your shadow library was written properly, the \"getpw*()\"\nfunctions described in perlfunc should in theory provide (read-only) access to entries in the\nshadow password file. To change the file, make a new shadow password file (the format varies\nfrom system to system--see passwd(1) for specifics) and use pwdmkdb(8) to install it (see\npwdmkdb(8) for more details).\n"
                    },
                    {
                        "name": "How do I set the time and date?",
                        "content": "Assuming you're running under sufficient permissions, you should be able to set the system-\nwide date and time by running the date(1) program. (There is no way to set the time and date\non a per-process basis.)  This mechanism will work for Unix, MS-DOS, Windows, and NT; the VMS\nequivalent is \"set time\".\n\nHowever, if all you want to do is change your time zone, you can probably get away with\nsetting an environment variable:\n\n$ENV{TZ} = \"MST7MDT\";           # Unixish\n$ENV{'SYS$TIMEZONEDIFFERENTIAL'}=\"-5\" # vms\nsystem('trn', 'comp.lang.perl.misc');\n"
                    },
                    {
                        "name": "How can I sleep() or alarm() for under a second?",
                        "content": "If you want finer granularity than the 1 second that the \"sleep()\" function provides, the\neasiest way is to use the \"select()\" function as documented in \"select\" in perlfunc. Try the\nTime::HiRes and the BSD::Itimer modules (available from CPAN, and starting from Perl 5.8\nTime::HiRes is part of the standard distribution).\n"
                    },
                    {
                        "name": "How can I measure time under a second?",
                        "content": "(contributed by brian d foy)\n\nThe Time::HiRes module (part of the standard distribution as of Perl 5.8) measures time with\nthe \"gettimeofday()\" system call, which returns the time in microseconds since the epoch. If\nyou can't install Time::HiRes for older Perls and you are on a Unixish system, you may be\nable to call gettimeofday(2) directly. See \"syscall\" in perlfunc.\n"
                    },
                    {
                        "name": "How can I do an atexit() or setjmp()/longjmp()? (Exception handling)",
                        "content": "You can use the \"END\" block to simulate \"atexit()\". Each package's \"END\" block is called when\nthe program or thread ends. See the perlmod manpage for more details about \"END\" blocks.\n\nFor example, you can use this to make sure your filter program managed to finish its output\nwithout filling up the disk:\n\nEND {\nclose(STDOUT) || die \"stdout close failed: $!\";\n}\n\nThe \"END\" block isn't called when untrapped signals kill the program, though, so if you use\n\"END\" blocks you should also use\n\nuse sigtrap qw(die normal-signals);\n\nPerl's exception-handling mechanism is its \"eval()\" operator. You can use \"eval()\" as\n\"setjmp\" and \"die()\" as \"longjmp\". For details of this, see the section on signals,\nespecially the time-out handler for a blocking \"flock()\" in \"Signals\" in perlipc or the\nsection on \"Signals\" in Programming Perl.\n\nIf exception handling is all you're interested in, use one of the many CPAN modules that\nhandle exceptions, such as Try::Tiny.\n\nIf you want the \"atexit()\" syntax (and an \"rmexit()\" as well), try the \"AtExit\" module\navailable from CPAN.\n"
                    },
                    {
                        "name": "Why doesn't my sockets program work under System V (Solaris)? What does the error message",
                        "content": ""
                    },
                    {
                        "name": "\"Protocol not supported\" mean?",
                        "content": "Some Sys-V based systems, notably Solaris 2.X, redefined some of the standard socket\nconstants. Since these were constant across all architectures, they were often hardwired into\nperl code. The proper way to deal with this is to \"use Socket\" to get the correct values.\n\nNote that even though SunOS and Solaris are binary compatible, these values are different. Go\nfigure.\n"
                    },
                    {
                        "name": "How can I call my system's unique C functions from Perl?",
                        "content": "In most cases, you write an external module to do it--see the answer to \"Where can I learn\nabout linking C with Perl? [h2xs, xsubpp]\".  However, if the function is a system call, and\nyour system supports \"syscall()\", you can use the \"syscall\" function (documented in\nperlfunc).\n\nRemember to check the modules that came with your distribution, and CPAN as well--someone may\nalready have written a module to do it. On Windows, try Win32::API. On Macs, try Mac::Carbon.\nIf no module has an interface to the C function, you can inline a bit of C in your Perl\nsource with Inline::C.\n"
                    },
                    {
                        "name": "Where do I get the include files to do ioctl() or syscall()?",
                        "content": "Historically, these would be generated by the h2ph tool, part of the standard perl\ndistribution. This program converts cpp(1) directives in C header files to files containing\nsubroutine definitions, like \"SYSgetitimer()\", which you can use as arguments to your\nfunctions.  It doesn't work perfectly, but it usually gets most of the job done.  Simple\nfiles like errno.h, syscall.h, and socket.h were fine, but the hard ones like ioctl.h nearly\nalways need to be hand-edited.  Here's how to install the *.ph files:\n\n1. Become the super-user\n2. cd /usr/include\n3. h2ph *.h */*.h\n\nIf your system supports dynamic loading, for reasons of portability and sanity you probably\nought to use h2xs (also part of the standard perl distribution). This tool converts C header\nfiles to Perl extensions.  See perlxstut for how to get started with h2xs.\n\nIf your system doesn't support dynamic loading, you still probably ought to use h2xs. See\nperlxstut and ExtUtils::MakeMaker for more information (in brief, just use make perl instead\nof a plain make to rebuild perl with a new static extension).\n"
                    },
                    {
                        "name": "Why do setuid perl scripts complain about kernel problems?",
                        "content": "Some operating systems have bugs in the kernel that make setuid scripts inherently insecure.\nPerl gives you a number of options (described in perlsec) to work around such systems.\n"
                    },
                    {
                        "name": "How can I open a pipe both to and from a command?",
                        "content": "The IPC::Open2 module (part of the standard perl distribution) is an easy-to-use approach\nthat internally uses \"pipe()\", \"fork()\", and \"exec()\" to do the job. Make sure you read the\ndeadlock warnings in its documentation, though (see IPC::Open2). See \"Bidirectional\nCommunication with Another Process\" in perlipc and \"Bidirectional Communication with\nYourself\" in perlipc\n\nYou may also use the IPC::Open3 module (part of the standard perl distribution), but be\nwarned that it has a different order of arguments from IPC::Open2 (see IPC::Open3).\n"
                    },
                    {
                        "name": "Why can't I get the output of a command with system()?",
                        "content": "You're confusing the purpose of \"system()\" and backticks (``). \"system()\" runs a command and\nreturns exit status information (as a 16 bit value: the low 7 bits are the signal the process\ndied from, if any, and the high 8 bits are the actual exit value). Backticks (``) run a\ncommand and return what it sent to STDOUT.\n\nmy $exitstatus   = system(\"mail-users\");\nmy $outputstring = `ls`;\n"
                    },
                    {
                        "name": "How can I capture STDERR from an external command?",
                        "content": "There are three basic ways of running external commands:\n\nsystem $cmd;        # using system()\nmy $output = `$cmd`;        # using backticks (``)\nopen (my $pipefh, \"$cmd |\");    # using open()\n\nWith \"system()\", both STDOUT and STDERR will go the same place as the script's STDOUT and\nSTDERR, unless the \"system()\" command redirects them.  Backticks and \"open()\" read only the\nSTDOUT of your command.\n\nYou can also use the \"open3()\" function from IPC::Open3. Benjamin Goldberg provides some\nsample code:\n\nTo capture a program's STDOUT, but discard its STDERR:\n\nuse IPC::Open3;\nuse File::Spec;\nmy $in = '';\nopen(NULL, \">\", File::Spec->devnull);\nmy $pid = open3($in, \\*PH, \">&NULL\", \"cmd\");\nwhile( <PH> ) { }\nwaitpid($pid, 0);\n\nTo capture a program's STDERR, but discard its STDOUT:\n\nuse IPC::Open3;\nuse File::Spec;\nmy $in = '';\nopen(NULL, \">\", File::Spec->devnull);\nmy $pid = open3($in, \">&NULL\", \\*PH, \"cmd\");\nwhile( <PH> ) { }\nwaitpid($pid, 0);\n\nTo capture a program's STDERR, and let its STDOUT go to our own STDERR:\n\nuse IPC::Open3;\nmy $in = '';\nmy $pid = open3($in, \">&STDERR\", \\*PH, \"cmd\");\nwhile( <PH> ) { }\nwaitpid($pid, 0);\n\nTo read both a command's STDOUT and its STDERR separately, you can redirect them to temp\nfiles, let the command run, then read the temp files:\n\nuse IPC::Open3;\nuse IO::File;\nmy $in = '';\nlocal *CATCHOUT = IO::File->newtmpfile;\nlocal *CATCHERR = IO::File->newtmpfile;\nmy $pid = open3($in, \">&CATCHOUT\", \">&CATCHERR\", \"cmd\");\nwaitpid($pid, 0);\nseek $, 0, 0 for \\*CATCHOUT, \\*CATCHERR;\nwhile( <CATCHOUT> ) {}\nwhile( <CATCHERR> ) {}\n\nBut there's no real need for both to be tempfiles... the following should work just as well,\nwithout deadlocking:\n\nuse IPC::Open3;\nmy $in = '';\nuse IO::File;\nlocal *CATCHERR = IO::File->newtmpfile;\nmy $pid = open3($in, \\*CATCHOUT, \">&CATCHERR\", \"cmd\");\nwhile( <CATCHOUT> ) {}\nwaitpid($pid, 0);\nseek CATCHERR, 0, 0;\nwhile( <CATCHERR> ) {}\n\nAnd it'll be faster, too, since we can begin processing the program's stdout immediately,\nrather than waiting for the program to finish.\n\nWith any of these, you can change file descriptors before the call:\n\nopen(STDOUT, \">logfile\");\nsystem(\"ls\");\n\nor you can use Bourne shell file-descriptor redirection:\n\n$output = `$cmd 2>somefile`;\nopen (PIPE, \"cmd 2>somefile |\");\n\nYou can also use file-descriptor redirection to make STDERR a duplicate of STDOUT:\n\n$output = `$cmd 2>&1`;\nopen (PIPE, \"cmd 2>&1 |\");\n\nNote that you cannot simply open STDERR to be a dup of STDOUT in your Perl program and avoid\ncalling the shell to do the redirection.  This doesn't work:\n\nopen(STDERR, \">&STDOUT\");\n$alloutput = `cmd args`;  # stderr still escapes\n\nThis fails because the \"open()\" makes STDERR go to where STDOUT was going at the time of the\n\"open()\". The backticks then make STDOUT go to a string, but don't change STDERR (which still\ngoes to the old STDOUT).\n\nNote that you must use Bourne shell (sh(1)) redirection syntax in backticks, not csh(1)!\nDetails on why Perl's \"system()\" and backtick and pipe opens all use the Bourne shell are in\nthe versus/csh.whynot article in the \"Far More Than You Ever Wanted To Know\" collection in\n<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> . To capture a command's STDERR and STDOUT\ntogether:\n\n$output = `cmd 2>&1`;                       # either with backticks\n$pid = open(PH, \"cmd 2>&1 |\");              # or with an open pipe\nwhile (<PH>) { }                            #    plus a read\n\nTo capture a command's STDOUT but discard its STDERR:\n\n$output = `cmd 2>/dev/null`;                # either with backticks\n$pid = open(PH, \"cmd 2>/dev/null |\");       # or with an open pipe\nwhile (<PH>) { }                            #    plus a read\n\nTo capture a command's STDERR but discard its STDOUT:\n\n$output = `cmd 2>&1 1>/dev/null`;           # either with backticks\n$pid = open(PH, \"cmd 2>&1 1>/dev/null |\");  # or with an open pipe\nwhile (<PH>) { }                            #    plus a read\n\nTo exchange a command's STDOUT and STDERR in order to capture the STDERR but leave its STDOUT\nto come out our old STDERR:\n\n$output = `cmd 3>&1 1>&2 2>&3 3>&-`;        # either with backticks\n$pid = open(PH, \"cmd 3>&1 1>&2 2>&3 3>&-|\");# or with an open pipe\nwhile (<PH>) { }                            #    plus a read\n\nTo read both a command's STDOUT and its STDERR separately, it's easiest to redirect them\nseparately to files, and then read from those files when the program is done:\n\nsystem(\"program args 1>program.stdout 2>program.stderr\");\n\nOrdering is important in all these examples. That's because the shell processes file\ndescriptor redirections in strictly left to right order.\n\nsystem(\"prog args 1>tmpfile 2>&1\");\nsystem(\"prog args 2>&1 1>tmpfile\");\n\nThe first command sends both standard out and standard error to the temporary file. The\nsecond command sends only the old standard output there, and the old standard error shows up\non the old standard out.\n"
                    },
                    {
                        "name": "Why doesn't open() return an error when a pipe open fails?",
                        "content": "If the second argument to a piped \"open()\" contains shell metacharacters, perl \"fork()\"s,\nthen \"exec()\"s a shell to decode the metacharacters and eventually run the desired program.\nIf the program couldn't be run, it's the shell that gets the message, not Perl. All your Perl\nprogram can find out is whether the shell itself could be successfully started. You can still\ncapture the shell's STDERR and check it for error messages. See \"How can I capture STDERR\nfrom an external command?\" elsewhere in this document, or use the IPC::Open3 module.\n\nIf there are no shell metacharacters in the argument of \"open()\", Perl runs the command\ndirectly, without using the shell, and can correctly report whether the command started.\n"
                    },
                    {
                        "name": "What's wrong with using backticks in a void context?",
                        "content": "Strictly speaking, nothing. Stylistically speaking, it's not a good way to write maintainable\ncode. Perl has several operators for running external commands. Backticks are one; they\ncollect the output from the command for use in your program. The \"system\" function is\nanother; it doesn't do this.\n\nWriting backticks in your program sends a clear message to the readers of your code that you\nwanted to collect the output of the command.  Why send a clear message that isn't true?\n\nConsider this line:\n\n`cat /etc/termcap`;\n\nYou forgot to check $? to see whether the program even ran correctly. Even if you wrote\n\nprint `cat /etc/termcap`;\n\nthis code could and probably should be written as\n\nsystem(\"cat /etc/termcap\") == 0\nor die \"cat program failed!\";\n\nwhich will echo the cat command's output as it is generated, instead of waiting until the\nprogram has completed to print it out. It also checks the return value.\n\n\"system\" also provides direct control over whether shell wildcard processing may take place,\nwhereas backticks do not.\n"
                    },
                    {
                        "name": "How can I call backticks without shell processing?",
                        "content": "This is a bit tricky. You can't simply write the command like this:\n\n@ok = `grep @opts '$searchstring' @filenames`;\n\nAs of Perl 5.8.0, you can use \"open()\" with multiple arguments.  Just like the list forms of\n\"system()\" and \"exec()\", no shell escapes happen.\n\nopen( GREP, \"-|\", 'grep', @opts, $searchstring, @filenames );\nchomp(@ok = <GREP>);\nclose GREP;\n\nYou can also:\n\nmy @ok = ();\nif (open(GREP, \"-|\")) {\nwhile (<GREP>) {\nchomp;\npush(@ok, $);\n}\nclose GREP;\n} else {\nexec 'grep', @opts, $searchstring, @filenames;\n}\n\nJust as with \"system()\", no shell escapes happen when you \"exec()\" a list. Further examples\nof this can be found in \"Safe Pipe Opens\" in perlipc.\n\nNote that if you're using Windows, no solution to this vexing issue is even possible. Even\nthough Perl emulates \"fork()\", you'll still be stuck, because Windows does not have an\nargc/argv-style API.\n"
                    },
                    {
                        "name": "Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?",
                        "content": "This happens only if your perl is compiled to use stdio instead of perlio, which is the\ndefault. Some (maybe all?) stdios set error and eof flags that you may need to clear. The\nPOSIX module defines \"clearerr()\" that you can use. That is the technically correct way to do\nit. Here are some less reliable workarounds:\n\n1.  Try keeping around the seekpointer and go there, like this:\n\nmy $where = tell($logfh);\nseek($logfh, $where, 0);\n\n2.  If that doesn't work, try seeking to a different part of the file and then back.\n\n3.  If that doesn't work, try seeking to a different part of the file, reading something, and\nthen seeking back.\n\n4.  If that doesn't work, give up on your stdio package and use sysread.\n"
                    },
                    {
                        "name": "How can I convert my shell script to perl?",
                        "content": "Learn Perl and rewrite it. Seriously, there's no simple converter.  Things that are awkward\nto do in the shell are easy to do in Perl, and this very awkwardness is what would make a\nshell->perl converter nigh-on impossible to write. By rewriting it, you'll think about what\nyou're really trying to do, and hopefully will escape the shell's pipeline datastream\nparadigm, which while convenient for some matters, causes many inefficiencies.\n"
                    },
                    {
                        "name": "Can I use perl to run a telnet or ftp session?",
                        "content": "Try the Net::FTP, TCP::Client, and Net::Telnet modules (available from CPAN).\n<http://www.cpan.org/scripts/netstuff/telnet.emul.shar> will also help for emulating the\ntelnet protocol, but Net::Telnet is quite probably easier to use.\n\nIf all you want to do is pretend to be telnet but don't need the initial telnet handshaking,\nthen the standard dual-process approach will suffice:\n\nuse IO::Socket;             # new in 5.004\nmy $handle = IO::Socket::INET->new('www.perl.com:80')\nor die \"can't connect to port 80 on www.perl.com $!\";\n$handle->autoflush(1);\nif (fork()) {               # XXX: undef means failure\nselect($handle);\nprint while <STDIN>;    # everything from stdin to socket\n} else {\nprint while <$handle>;  # everything from socket to stdout\n}\nclose $handle;\nexit;\n"
                    },
                    {
                        "name": "How can I write expect in Perl?",
                        "content": "Once upon a time, there was a library called chat2.pl (part of the standard perl\ndistribution), which never really got finished. If you find it somewhere, don't use it. These\ndays, your best bet is to look at the Expect module available from CPAN, which also requires\ntwo other modules from CPAN, IO::Pty and IO::Stty.\n"
                    },
                    {
                        "name": "Is there a way to hide perl's command line from programs such as \"ps\"?",
                        "content": "First of all note that if you're doing this for security reasons (to avoid people seeing\npasswords, for example) then you should rewrite your program so that critical information is\nnever given as an argument. Hiding the arguments won't make your program completely secure.\n\nTo actually alter the visible command line, you can assign to the variable $0 as documented\nin perlvar. This won't work on all operating systems, though. Daemon programs like sendmail\nplace their state there, as in:\n\n$0 = \"orcus [accepting connections]\";\n"
                    },
                    {
                        "name": "I {changed directory, modified my environment} in a perl script. How come the change disappeared",
                        "content": ""
                    },
                    {
                        "name": "when I exited the script? How do I get my changes to be visible?",
                        "content": "Unix\nIn the strictest sense, it can't be done--the script executes as a different process from\nthe shell it was started from. Changes to a process are not reflected in its parent--only\nin any children created after the change. There is shell magic that may allow you to fake\nit by \"eval()\"ing the script's output in your shell; check out the comp.unix.questions\nFAQ for details.\n"
                    },
                    {
                        "name": "How do I close a process's filehandle without waiting for it to complete?",
                        "content": "Assuming your system supports such things, just send an appropriate signal to the process\n(see \"kill\" in perlfunc). It's common to first send a TERM signal, wait a little bit, and\nthen send a KILL signal to finish it off.\n"
                    },
                    {
                        "name": "How do I fork a daemon process?",
                        "content": "If by daemon process you mean one that's detached (disassociated from its tty), then the\nfollowing process is reported to work on most Unixish systems. Non-Unix users should check\ntheir YourOS::Process module for other solutions.\n\n•   Open /dev/tty and use the TIOCNOTTY ioctl on it. See tty(1) for details. Or better yet,\nyou can just use the \"POSIX::setsid()\" function, so you don't have to worry about process\ngroups.\n\n•   Change directory to /\n\n•   Reopen STDIN, STDOUT, and STDERR so they're not connected to the old tty.\n\n•   Background yourself like this:\n\nfork && exit;\n\nThe Proc::Daemon module, available from CPAN, provides a function to perform these actions\nfor you.\n"
                    },
                    {
                        "name": "How do I find out if I'm running interactively or not?",
                        "content": "(contributed by brian d foy)\n\nThis is a difficult question to answer, and the best answer is only a guess.\n\nWhat do you really want to know? If you merely want to know if one of your filehandles is\nconnected to a terminal, you can try the \"-t\" file test:\n\nif( -t STDOUT ) {\nprint \"I'm connected to a terminal!\\n\";\n}\n\nHowever, you might be out of luck if you expect that means there is a real person on the\nother side. With the Expect module, another program can pretend to be a person. The program\nmight even come close to passing the Turing test.\n\nThe IO::Interactive module does the best it can to give you an answer. Its \"isinteractive\"\nfunction returns an output filehandle; that filehandle points to standard output if the\nmodule thinks the session is interactive. Otherwise, the filehandle is a null handle that\nsimply discards the output:\n\nuse IO::Interactive;\n\nprint { isinteractive } \"I might go to standard output!\\n\";\n\nThis still doesn't guarantee that a real person is answering your prompts or reading your\noutput.\n\nIf you want to know how to handle automated testing for your distribution, you can check the\nenvironment. The CPAN Testers, for instance, set the value of \"AUTOMATEDTESTING\":\n\nunless( $ENV{AUTOMATEDTESTING} ) {\nprint \"Hello interactive tester!\\n\";\n}\n"
                    },
                    {
                        "name": "How do I timeout a slow event?",
                        "content": "Use the \"alarm()\" function, probably in conjunction with a signal handler, as documented in\n\"Signals\" in perlipc and the section on \"Signals\" in the Camel. You may instead use the more\nflexible Sys::AlarmCall module available from CPAN.\n\nThe \"alarm()\" function is not implemented on all versions of Windows.  Check the\ndocumentation for your specific version of Perl.\n"
                    },
                    {
                        "name": "How do I set CPU limits?",
                        "content": "(contributed by Xho)\n\nUse the BSD::Resource module from CPAN. As an example:\n\nuse BSD::Resource;\nsetrlimit(RLIMITCPU,10,20) or die $!;\n\nThis sets the soft and hard limits to 10 and 20 seconds, respectively.  After 10 seconds of\ntime spent running on the CPU (not \"wall\" time), the process will be sent a signal (XCPU on\nsome systems) which, if not trapped, will cause the process to terminate. If that signal is\ntrapped, then after 10 more seconds (20 seconds in total) the process will be killed with a\nnon-trappable signal.\n\nSee the BSD::Resource and your systems documentation for the gory details.\n"
                    },
                    {
                        "name": "How do I avoid zombies on a Unix system?",
                        "content": "Use the reaper code from \"Signals\" in perlipc to call \"wait()\" when a SIGCHLD is received, or\nelse use the double-fork technique described in \"How do I start a process in the background?\"\nin perlfaq8.\n"
                    },
                    {
                        "name": "How do I use an SQL database?",
                        "content": "The DBI module provides an abstract interface to most database servers and types, including\nOracle, DB2, Sybase, mysql, Postgresql, ODBC, and flat files. The DBI module accesses each\ndatabase type through a database driver, or DBD. You can see a complete list of available\ndrivers on CPAN: <http://www.cpan.org/modules/by-module/DBD/> .  You can read more about DBI\non <http://dbi.perl.org/> .\n\nOther modules provide more specific access: Win32::ODBC, Alzabo, \"iodbc\", and others found on\nCPAN Search: <https://metacpan.org/> .\n"
                    },
                    {
                        "name": "How do I make a system() exit on control-C?",
                        "content": "You can't. You need to imitate the \"system()\" call (see perlipc for sample code) and then\nhave a signal handler for the INT signal that passes the signal on to the subprocess. Or you\ncan check for it:\n\n$rc = system($cmd);\nif ($rc & 127) { die \"signal death\" }\n"
                    },
                    {
                        "name": "How do I open a file without blocking?",
                        "content": "If you're lucky enough to be using a system that supports non-blocking reads (most Unixish\nsystems do), you need only to use the \"ONDELAY\" or \"ONONBLOCK\" flag from the \"Fcntl\" module\nin conjunction with \"sysopen()\":\n\nuse Fcntl;\nsysopen(my $fh, \"/foo/somefile\", OWRONLY|ONDELAY|OCREAT, 0644)\nor die \"can't open /foo/somefile: $!\":\n"
                    },
                    {
                        "name": "How do I tell the difference between errors from the shell and perl?",
                        "content": "(answer contributed by brian d foy)\n\nWhen you run a Perl script, something else is running the script for you, and that something\nelse may output error messages. The script might emit its own warnings and error messages.\nMost of the time you cannot tell who said what.\n\nYou probably cannot fix the thing that runs perl, but you can change how perl outputs its\nwarnings by defining a custom warning and die functions.\n\nConsider this script, which has an error you may not notice immediately.\n\n#!/usr/locl/bin/perl\n\nprint \"Hello World\\n\";\n\nI get an error when I run this from my shell (which happens to be bash). That may look like\nperl forgot it has a \"print()\" function, but my shebang line is not the path to perl, so the\nshell runs the script, and I get the error.\n\n$ ./test\n./test: line 3: print: command not found\n\nA quick and dirty fix involves a little bit of code, but this may be all you need to figure\nout the problem.\n\n#!/usr/bin/perl -w\n\nBEGIN {\n$SIG{WARN} = sub{ print STDERR \"Perl: \", @; };\n$SIG{DIE}  = sub{ print STDERR \"Perl: \", @; exit 1};\n}\n\n$a = 1 + undef;\n$x / 0;\nEND\n\nThe perl message comes out with \"Perl\" in front. The \"BEGIN\" block works at compile time so\nall of the compilation errors and warnings get the \"Perl:\" prefix too.\n\nPerl: Useless use of division (/) in void context at ./test line 9.\nPerl: Name \"main::a\" used only once: possible typo at ./test line 8.\nPerl: Name \"main::x\" used only once: possible typo at ./test line 9.\nPerl: Use of uninitialized value in addition (+) at ./test line 8.\nPerl: Use of uninitialized value in division (/) at ./test line 9.\nPerl: Illegal division by zero at ./test line 9.\nPerl: Illegal division by zero at -e line 3.\n\nIf I don't see that \"Perl:\", it's not from perl.\n\nYou could also just know all the perl errors, and although there are some people who may know\nall of them, you probably don't. However, they all should be in the perldiag manpage. If you\ndon't find the error in there, it probably isn't a perl error.\n\nLooking up every message is not the easiest way, so let perl to do it for you. Use the\ndiagnostics pragma with turns perl's normal messages into longer discussions on the topic.\n\nuse diagnostics;\n\nIf you don't get a paragraph or two of expanded discussion, it might not be perl's message.\n"
                    },
                    {
                        "name": "How do I install a module from CPAN?",
                        "content": "(contributed by brian d foy)\n\nThe easiest way is to have a module also named CPAN do it for you by using the \"cpan\" command\nthat comes with Perl. You can give it a list of modules to install:\n\n$ cpan IO::Interactive Getopt::Whatever\n\nIf you prefer \"CPANPLUS\", it's just as easy:\n\n$ cpanp i IO::Interactive Getopt::Whatever\n\nIf you want to install a distribution from the current directory, you can tell \"CPAN.pm\" to\ninstall \".\" (the full stop):\n\n$ cpan .\n\nSee the documentation for either of those commands to see what else you can do.\n\nIf you want to try to install a distribution by yourself, resolving all dependencies on your\nown, you follow one of two possible build paths.\n\nFor distributions that use Makefile.PL:\n\n$ perl Makefile.PL\n$ make test install\n\nFor distributions that use Build.PL:\n\n$ perl Build.PL\n$ ./Build test\n$ ./Build install\n\nSome distributions may need to link to libraries or other third-party code and their build\nand installation sequences may be more complicated.  Check any README or INSTALL files that\nyou may find.\n"
                    },
                    {
                        "name": "What's the difference between require and use?",
                        "content": "(contributed by brian d foy)\n\nPerl runs \"require\" statement at run-time. Once Perl loads, compiles, and runs the file, it\ndoesn't do anything else. The \"use\" statement is the same as a \"require\" run at compile-time,\nbut Perl also calls the \"import\" method for the loaded package. These two are the same:\n\nuse MODULE qw(import list);\n\nBEGIN {\nrequire MODULE;\nMODULE->import(import list);\n}\n\nHowever, you can suppress the \"import\" by using an explicit, empty import list. Both of these\nstill happen at compile-time:\n\nuse MODULE ();\n\nBEGIN {\nrequire MODULE;\n}\n\nSince \"use\" will also call the \"import\" method, the actual value for \"MODULE\" must be a\nbareword. That is, \"use\" cannot load files by name, although \"require\" can:\n\nrequire \"$ENV{HOME}/lib/Foo.pm\"; # no @INC searching!\n\nSee the entry for \"use\" in perlfunc for more details.\n"
                    },
                    {
                        "name": "How do I keep my own module/library directory?",
                        "content": "When you build modules, tell Perl where to install the modules.\n\nIf you want to install modules for your own use, the easiest way might be local::lib, which\nyou can download from CPAN. It sets various installation settings for you, and uses those\nsame settings within your programs.\n\nIf you want more flexibility, you need to configure your CPAN client for your particular\nsituation.\n\nFor \"Makefile.PL\"-based distributions, use the INSTALLBASE option when generating Makefiles:\n\nperl Makefile.PL INSTALLBASE=/mydir/perl\n\nYou can set this in your \"CPAN.pm\" configuration so modules automatically install in your\nprivate library directory when you use the CPAN.pm shell:\n\n% cpan\ncpan> o conf makeplarg INSTALLBASE=/mydir/perl\ncpan> o conf commit\n\nFor \"Build.PL\"-based distributions, use the --installbase option:\n\nperl Build.PL --installbase /mydir/perl\n\nYou can configure \"CPAN.pm\" to automatically use this option too:\n\n% cpan\ncpan> o conf mbuildarg \"--installbase /mydir/perl\"\ncpan> o conf commit\n\nINSTALLBASE tells these tools to put your modules into /mydir/perl/lib/perl5. See \"How do I\nadd a directory to my include path (@INC) at runtime?\" for details on how to run your newly\ninstalled modules.\n\nThere is one caveat with INSTALLBASE, though, since it acts differently from the PREFIX and\nLIB settings that older versions of ExtUtils::MakeMaker advocated. INSTALLBASE does not\nsupport installing modules for multiple versions of Perl or different architectures under the\nsame directory. You should consider whether you really want that and, if you do, use the\nolder PREFIX and LIB settings. See the ExtUtils::Makemaker documentation for more details.\n"
                    },
                    {
                        "name": "How do I add the directory my program lives in to the module/library search path?",
                        "content": "(contributed by brian d foy)\n\nIf you know the directory already, you can add it to @INC as you would for any other\ndirectory. You might \"use lib\" if you know the directory at compile time:\n\nuse lib $directory;\n\nThe trick in this task is to find the directory. Before your script does anything else (such\nas a \"chdir\"), you can get the current working directory with the \"Cwd\" module, which comes\nwith Perl:\n\nBEGIN {\nuse Cwd;\nour $directory = cwd;\n}\n\nuse lib $directory;\n\nYou can do a similar thing with the value of $0, which holds the script name. That might hold\na relative path, but \"rel2abs\" can turn it into an absolute path. Once you have the\n\nBEGIN {\nuse File::Spec::Functions qw(rel2abs);\nuse File::Basename qw(dirname);\n\nmy $path   = rel2abs( $0 );\nour $directory = dirname( $path );\n}\n\nuse lib $directory;\n\nThe FindBin module, which comes with Perl, might work. It finds the directory of the\ncurrently running script and puts it in $Bin, which you can then use to construct the right\nlibrary path:\n\nuse FindBin qw($Bin);\n\nYou can also use local::lib to do much of the same thing. Install modules using local::lib's\nsettings then use the module in your program:\n\nuse local::lib; # sets up a local lib at ~/perl5\n\nSee the local::lib documentation for more details.\n"
                    },
                    {
                        "name": "How do I add a directory to my include path (@INC) at runtime?",
                        "content": "Here are the suggested ways of modifying your include path, including environment variables,\nrun-time switches, and in-code statements:\n\nthe \"PERLLIB\" environment variable\n$ export PERLLIB=/path/to/my/dir\n$ perl program.pl\n\nthe \"PERL5LIB\" environment variable\n$ export PERL5LIB=/path/to/my/dir\n$ perl program.pl\n\nthe \"perl -Idir\" command line flag\n$ perl -I/path/to/my/dir program.pl\n\nthe \"lib\" pragma:\nuse lib \"$ENV{HOME}/myownperllib\";\n\nthe local::lib module:\nuse local::lib;\n\nuse local::lib \"~/myownperllib\";\n"
                    },
                    {
                        "name": "Where are modules installed?",
                        "content": "Modules are installed on a case-by-case basis (as provided by the methods described in the\nprevious section), and in the operating system. All of these paths are stored in @INC, which\nyou can display with the one-liner\n\nperl -e 'print join(\"\\n\",@INC,\"\")'\n\nThe same information is displayed at the end of the output from the command\n\nperl -V\n\nTo find out where a module's source code is located, use\n\nperldoc -l Encode\n\nto display the path to the module. In some cases (for example, the \"AutoLoader\" module), this\ncommand will show the path to a separate \"pod\" file; the module itself should be in the same\ndirectory, with a 'pm' file extension.\n"
                    },
                    {
                        "name": "What is socket.ph and where do I get it?",
                        "content": "It's a Perl 4 style file defining values for system networking constants. Sometimes it is\nbuilt using h2ph when Perl is installed, but other times it is not. Modern programs should\nuse \"use Socket;\" instead.\n"
                    }
                ]
            },
            "AUTHOR AND COPYRIGHT": {
                "content": "Copyright (c) 1997-2010 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\n\n\nperl v5.34.0                                 2026-06-23                                  PERLFAQ8(1)",
                "subsections": []
            }
        }
    }
}