{
    "content": [
        {
            "type": "text",
            "text": "# perlfaq5 (man)\n\n## NAME\n\nperlfaq5 - Files and Formats\n\n## DESCRIPTION\n\nThis section deals with I/O and the \"f\" issues: filehandles, flushing, formats, and footers.\n\n## Sections\n\n- **NAME**\n- **VERSION**\n- **DESCRIPTION** (43 subsections)\n- **AUTHOR AND COPYRIGHT**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "perlfaq5",
        "section": "",
        "mode": "man",
        "summary": "perlfaq5 - Files and Formats",
        "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": 2,
                "subsections": [
                    {
                        "name": "How do I flush/unbuffer an output filehandle? Why must I do this?",
                        "lines": 79
                    },
                    {
                        "name": "How do I change, delete, or insert a line in a file, or append to the beginning of a file?",
                        "lines": 138
                    },
                    {
                        "name": "How do I count the number of lines in a file?",
                        "lines": 53
                    },
                    {
                        "name": "How do I delete the last N lines from a file?",
                        "lines": 38
                    },
                    {
                        "name": "How can I use Perl's \"-i\" option from within a program?",
                        "lines": 21
                    },
                    {
                        "name": "How can I copy a file?",
                        "lines": 13
                    },
                    {
                        "name": "How do I make a temporary file name?",
                        "lines": 53
                    },
                    {
                        "name": "How can I manipulate fixed-record-length files?",
                        "lines": 25
                    },
                    {
                        "name": "How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines?",
                        "lines": 1
                    },
                    {
                        "name": "How do I make an array of filehandles?",
                        "lines": 35
                    },
                    {
                        "name": "How can I use a filehandle indirectly?",
                        "lines": 83
                    },
                    {
                        "name": "How can I open a filehandle to a string?",
                        "lines": 15
                    },
                    {
                        "name": "How can I set up a footer format to be used with write()?",
                        "lines": 3
                    },
                    {
                        "name": "How can I write() into a string?",
                        "lines": 46
                    },
                    {
                        "name": "How can I output my numbers with commas added?",
                        "lines": 32
                    },
                    {
                        "name": "How can I translate tildes (~) in a filename?",
                        "lines": 19
                    },
                    {
                        "name": "How come when I open a file read-write it wipes it out?",
                        "lines": 80
                    },
                    {
                        "name": "How can I open a file named with a leading \">\" or trailing blanks?",
                        "lines": 12
                    },
                    {
                        "name": "How can I reliably rename a file?",
                        "lines": 10
                    },
                    {
                        "name": "How can I lock a file?",
                        "lines": 31
                    },
                    {
                        "name": "Why can't I just open(FH, \">file.lock\")?",
                        "lines": 16
                    },
                    {
                        "name": "I still don't get locking. I just want to increment the number in the file. How can I do this?",
                        "lines": 21
                    },
                    {
                        "name": "All I want to do is append a small amount of text to the end of a file. Do I still have to use",
                        "lines": 1
                    },
                    {
                        "name": "locking?",
                        "lines": 23
                    },
                    {
                        "name": "How do I randomly update a binary file?",
                        "lines": 19
                    },
                    {
                        "name": "How do I get a file's timestamp in perl?",
                        "lines": 26
                    },
                    {
                        "name": "How do I set a file's timestamp in perl?",
                        "lines": 21
                    },
                    {
                        "name": "How do I print to more than one file at once?",
                        "lines": 7
                    },
                    {
                        "name": "How can I read in an entire file all at once?",
                        "lines": 67
                    },
                    {
                        "name": "How can I read in a file by paragraphs?",
                        "lines": 7
                    },
                    {
                        "name": "How can I read a single character from a file? From the keyboard?",
                        "lines": 66
                    },
                    {
                        "name": "How can I tell whether there's a character waiting on a filehandle?",
                        "lines": 53
                    },
                    {
                        "name": "How do I do a \"tail -f\" in perl?",
                        "lines": 24
                    },
                    {
                        "name": "How do I dup() a filehandle in Perl?",
                        "lines": 16
                    },
                    {
                        "name": "How do I close a file descriptor by number?",
                        "lines": 22
                    },
                    {
                        "name": "Why can't I use \"C:\\temp\\foo\" in DOS paths? Why doesn't `C:\\temp\\foo.exe` work?",
                        "lines": 17
                    },
                    {
                        "name": "Why does Perl let me delete read-only files? Why does \"-i\" clobber protected files? Isn't this a",
                        "lines": 1
                    },
                    {
                        "name": "bug in Perl?",
                        "lines": 10
                    },
                    {
                        "name": "How do I select a random line from a file?",
                        "lines": 20
                    },
                    {
                        "name": "Why do I get weird spaces when I print an array of lines?",
                        "lines": 37
                    },
                    {
                        "name": "How do I traverse a directory tree?",
                        "lines": 38
                    },
                    {
                        "name": "How do I delete a directory tree?",
                        "lines": 15
                    },
                    {
                        "name": "How do I copy an entire directory?",
                        "lines": 6
                    }
                ]
            },
            {
                "name": "AUTHOR AND COPYRIGHT",
                "lines": 14,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "perlfaq5 - Files and Formats\n",
                "subsections": []
            },
            "VERSION": {
                "content": "version 5.20210411\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "This section deals with I/O and the \"f\" issues: filehandles, flushing, formats, and footers.\n",
                "subsections": [
                    {
                        "name": "How do I flush/unbuffer an output filehandle? Why must I do this?",
                        "content": "(contributed by brian d foy)\n\nYou might like to read Mark Jason Dominus's \"Suffering From Buffering\" at\n<http://perl.plover.com/FAQs/Buffering.html> .\n\nPerl normally buffers output so it doesn't make a system call for every bit of output. By\nsaving up output, it makes fewer expensive system calls.  For instance, in this little bit of\ncode, you want to print a dot to the screen for every line you process to watch the progress\nof your program.  Instead of seeing a dot for every line, Perl buffers the output and you\nhave a long wait before you see a row of 50 dots all at once:\n\n# long wait, then row of dots all at once\nwhile( <> ) {\nprint \".\";\nprint \"\\n\" unless ++$count % 50;\n\n#... expensive line processing operations\n}\n\nTo get around this, you have to unbuffer the output filehandle, in this case, \"STDOUT\". You\ncan set the special variable $| to a true value (mnemonic: making your filehandles \"piping\nhot\"):\n\n$|++;\n\n# dot shown immediately\nwhile( <> ) {\nprint \".\";\nprint \"\\n\" unless ++$count % 50;\n\n#... expensive line processing operations\n}\n\nThe $| is one of the per-filehandle special variables, so each filehandle has its own copy of\nits value. If you want to merge standard output and standard error for instance, you have to\nunbuffer each (although STDERR might be unbuffered by default):\n\n{\nmy $previousdefault = select(STDOUT);  # save previous default\n$|++;                                   # autoflush STDOUT\nselect(STDERR);\n$|++;                                   # autoflush STDERR, to be sure\nselect($previousdefault);              # restore previous default\n}\n\n# now should alternate . and +\nwhile( 1 ) {\nsleep 1;\nprint STDOUT \".\";\nprint STDERR \"+\";\nprint STDOUT \"\\n\" unless ++$count % 25;\n}\n\nBesides the $| special variable, you can use \"binmode\" to give your filehandle a \":unix\"\nlayer, which is unbuffered:\n\nbinmode( STDOUT, \":unix\" );\n\nwhile( 1 ) {\nsleep 1;\nprint \".\";\nprint \"\\n\" unless ++$count % 50;\n}\n\nFor more information on output layers, see the entries for \"binmode\" and open in perlfunc,\nand the PerlIO module documentation.\n\nIf you are using IO::Handle or one of its subclasses, you can call the \"autoflush\" method to\nchange the settings of the filehandle:\n\nuse IO::Handle;\nopen my( $iofh ), \">\", \"output.txt\";\n$iofh->autoflush(1);\n\nThe IO::Handle objects also have a \"flush\" method. You can flush the buffer any time you want\nwithout auto-buffering\n\n$iofh->flush;\n"
                    },
                    {
                        "name": "How do I change, delete, or insert a line in a file, or append to the beginning of a file?",
                        "content": "(contributed by brian d foy)\n\nThe basic idea of inserting, changing, or deleting a line from a text file involves reading\nand printing the file to the point you want to make the change, making the change, then\nreading and printing the rest of the file. Perl doesn't provide random access to lines\n(especially since the record input separator, $/, is mutable), although modules such as\nTie::File can fake it.\n\nA Perl program to do these tasks takes the basic form of opening a file, printing its lines,\nthen closing the file:\n\nopen my $in,  '<',  $file      or die \"Can't read old file: $!\";\nopen my $out, '>', \"$file.new\" or die \"Can't write new file: $!\";\n\nwhile( <$in> ) {\nprint $out $;\n}\n\nclose $out;\n\nWithin that basic form, add the parts that you need to insert, change, or delete lines.\n\nTo prepend lines to the beginning, print those lines before you enter the loop that prints\nthe existing lines.\n\nopen my $in,  '<',  $file      or die \"Can't read old file: $!\";\nopen my $out, '>', \"$file.new\" or die \"Can't write new file: $!\";\n\nprint $out \"# Add this line to the top\\n\"; # <--- HERE'S THE MAGIC\n\nwhile( <$in> ) {\nprint $out $;\n}\n\nclose $out;\n\nTo change existing lines, insert the code to modify the lines inside the \"while\" loop. In\nthis case, the code finds all lowercased versions of \"perl\" and uppercases them. The happens\nfor every line, so be sure that you're supposed to do that on every line!\n\nopen my $in,  '<',  $file      or die \"Can't read old file: $!\";\nopen my $out, '>', \"$file.new\" or die \"Can't write new file: $!\";\n\nprint $out \"# Add this line to the top\\n\";\n\nwhile( <$in> ) {\ns/\\b(perl)\\b/Perl/g;\nprint $out $;\n}\n\nclose $out;\n\nTo change only a particular line, the input line number, $., is useful. First read and print\nthe lines up to the one you  want to change. Next, read the single line you want to change,\nchange it, and print it. After that, read the rest of the lines and print those:\n\nwhile( <$in> ) { # print the lines before the change\nprint $out $;\nlast if $. == 4; # line number before change\n}\n\nmy $line = <$in>;\n$line =~ s/\\b(perl)\\b/Perl/g;\nprint $out $line;\n\nwhile( <$in> ) { # print the rest of the lines\nprint $out $;\n}\n\nTo skip lines, use the looping controls. The \"next\" in this example skips comment lines, and\nthe \"last\" stops all processing once it encounters either \"END\" or \"DATA\".\n\nwhile( <$in> ) {\nnext if /^\\s+#/;             # skip comment lines\nlast if /^(END|DATA)$/;  # stop at end of code marker\nprint $out $;\n}\n\nDo the same sort of thing to delete a particular line by using \"next\" to skip the lines you\ndon't want to show up in the output. This example skips every fifth line:\n\nwhile( <$in> ) {\nnext unless $. % 5;\nprint $out $;\n}\n\nIf, for some odd reason, you really want to see the whole file at once rather than processing\nline-by-line, you can slurp it in (as long as you can fit the whole thing in memory!):\n\nopen my $in,  '<',  $file      or die \"Can't read old file: $!\"\nopen my $out, '>', \"$file.new\" or die \"Can't write new file: $!\";\n\nmy $content = do { local $/; <$in> }; # slurp!\n\n# do your magic here\n\nprint $out $content;\n\nModules such as Path::Tiny and Tie::File can help with that too. If you can, however, avoid\nreading the entire file at once. Perl won't give that memory back to the operating system\nuntil the process finishes.\n\nYou can also use Perl one-liners to modify a file in-place. The following changes all 'Fred'\nto 'Barney' in inFile.txt, overwriting the file with the new contents. With the \"-p\" switch,\nPerl wraps a \"while\" loop around the code you specify with \"-e\", and \"-i\" turns on in-place\nediting. The current line is in $. With \"-p\", Perl automatically prints the value of $ at\nthe end of the loop. See perlrun for more details.\n\nperl -pi -e 's/Fred/Barney/' inFile.txt\n\nTo make a backup of \"inFile.txt\", give \"-i\" a file extension to add:\n\nperl -pi.bak -e 's/Fred/Barney/' inFile.txt\n\nTo change only the fifth line, you can add a test checking $., the input line number, then\nonly perform the operation when the test passes:\n\nperl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt\n\nTo add lines before a certain line, you can add a line (or lines!)  before Perl prints $:\n\nperl -pi -e 'print \"Put before third line\\n\" if $. == 3' inFile.txt\n\nYou can even add a line to the beginning of a file, since the current line prints at the end\nof the loop:\n\nperl -pi -e 'print \"Put before first line\\n\" if $. == 1' inFile.txt\n\nTo insert a line after one already in the file, use the \"-n\" switch.  It's just like \"-p\"\nexcept that it doesn't print $ at the end of the loop, so you have to do that yourself. In\nthis case, print $ first, then print the line that you want to add.\n\nperl -ni -e 'print; print \"Put after fifth line\\n\" if $. == 5' inFile.txt\n\nTo delete lines, only print the ones that you want.\n\nperl -ni -e 'print if /d/' inFile.txt\n"
                    },
                    {
                        "name": "How do I count the number of lines in a file?",
                        "content": "(contributed by brian d foy)\n\nConceptually, the easiest way to count the lines in a file is to simply read them and count\nthem:\n\nmy $count = 0;\nwhile( <$fh> ) { $count++; }\n\nYou don't really have to count them yourself, though, since Perl already does that with the\n$. variable, which is the current line number from the last filehandle read:\n\n1 while( <$fh> );\nmy $count = $.;\n\nIf you want to use $., you can reduce it to a simple one-liner, like one of these:\n\n% perl -lne '} print $.; {'    file\n\n% perl -lne 'END { print $. }' file\n\nThose can be rather inefficient though. If they aren't fast enough for you, you might just\nread chunks of data and count the number of newlines:\n\nmy $lines = 0;\nopen my($fh), '<:raw', $filename or die \"Can't open $filename: $!\";\nwhile( sysread $fh, $buffer, 4096 ) {\n$lines += ( $buffer =~ tr/\\n// );\n}\nclose $fh;\n\nHowever, that doesn't work if the line ending isn't a newline. You might change that \"tr///\"\nto a \"s///\" so you can count the number of times the input record separator, $/, shows up:\n\nmy $lines = 0;\nopen my($fh), '<:raw', $filename or die \"Can't open $filename: $!\";\nwhile( sysread $fh, $buffer, 4096 ) {\n$lines += ( $buffer =~ s|$/||g; );\n}\nclose $fh;\n\nIf you don't mind shelling out, the \"wc\" command is usually the fastest, even with the extra\ninterprocess overhead. Ensure that you have an untainted filename though:\n\n#!perl -T\n\n$ENV{PATH} = undef;\n\nmy $lines;\nif( $filename =~ /^([0-9a-z.]+)\\z/ ) {\n$lines = `/usr/bin/wc -l $1`\nchomp $lines;\n}\n"
                    },
                    {
                        "name": "How do I delete the last N lines from a file?",
                        "content": "(contributed by brian d foy)\n\nThe easiest conceptual solution is to count the lines in the file then start at the beginning\nand print the number of lines (minus the last N) to a new file.\n\nMost often, the real question is how you can delete the last N lines without making more than\none pass over the file, or how to do it without a lot of copying. The easy concept is the\nhard reality when you might have millions of lines in your file.\n\nOne trick is to use File::ReadBackwards, which starts at the end of the file. That module\nprovides an object that wraps the real filehandle to make it easy for you to move around the\nfile. Once you get to the spot you need, you can get the actual filehandle and work with it\nas normal. In this case, you get the file position at the end of the last line you want to\nkeep and truncate the file to that point:\n\nuse File::ReadBackwards;\n\nmy $filename = 'test.txt';\nmy $Linestotruncate = 2;\n\nmy $bw = File::ReadBackwards->new( $filename )\nor die \"Could not read backwards in [$filename]: $!\";\n\nmy $linesfromend = 0;\nuntil( $bw->eof or $linesfromend == $Linestotruncate ) {\nprint \"Got: \", $bw->readline;\n$linesfromend++;\n}\n\ntruncate( $filename, $bw->tell );\n\nThe File::ReadBackwards module also has the advantage of setting the input record separator\nto a regular expression.\n\nYou can also use the Tie::File module which lets you access the lines through a tied array.\nYou can use normal array operations to modify your file, including setting the last index and\nusing \"splice\".\n"
                    },
                    {
                        "name": "How can I use Perl's \"-i\" option from within a program?",
                        "content": "\"-i\" sets the value of Perl's $^I variable, which in turn affects the behavior of \"<>\"; see\nperlrun for more details. By modifying the appropriate variables directly, you can get the\nsame behavior within a larger program. For example:\n\n# ...\n{\nlocal($^I, @ARGV) = ('.orig', glob(\"*.c\"));\nwhile (<>) {\nif ($. == 1) {\nprint \"This line should appear at the top of each file\\n\";\n}\ns/\\b(p)earl\\b/${1}erl/i;        # Correct typos, preserving case\nprint;\nclose ARGV if eof;              # Reset $.\n}\n}\n# $^I and @ARGV return to their old values here\n\nThis block modifies all the \".c\" files in the current directory, leaving a backup of the\noriginal data from each file in a new \".c.orig\" file.\n"
                    },
                    {
                        "name": "How can I copy a file?",
                        "content": "(contributed by brian d foy)\n\nUse the File::Copy module. It comes with Perl and can do a true copy across file systems, and\nit does its magic in a portable fashion.\n\nuse File::Copy;\n\ncopy( $original, $newcopy ) or die \"Copy failed: $!\";\n\nIf you can't use File::Copy, you'll have to do the work yourself: open the original file,\nopen the destination file, then print to the destination file as you read the original. You\nalso have to remember to copy the permissions, owner, and group to the new file.\n"
                    },
                    {
                        "name": "How do I make a temporary file name?",
                        "content": "If you don't need to know the name of the file, you can use \"open()\" with \"undef\" in place of\nthe file name. In Perl 5.8 or later, the \"open()\" function creates an anonymous temporary\nfile:\n\nopen my $tmp, '+>', undef or die $!;\n\nOtherwise, you can use the File::Temp module.\n\nuse File::Temp qw/ tempfile tempdir /;\n\nmy $dir = tempdir( CLEANUP => 1 );\n($fh, $filename) = tempfile( DIR => $dir );\n\n# or if you don't need to know the filename\n\nmy $fh = tempfile( DIR => $dir );\n\nThe File::Temp has been a standard module since Perl 5.6.1. If you don't have a modern enough\nPerl installed, use the \"newtmpfile\" class method from the IO::File module to get a\nfilehandle opened for reading and writing. Use it if you don't need to know the file's name:\n\nuse IO::File;\nmy $fh = IO::File->newtmpfile()\nor die \"Unable to make new temporary file: $!\";\n\nIf you're committed to creating a temporary file by hand, use the process ID and/or the\ncurrent time-value. If you need to have many temporary files in one process, use a counter:\n\nBEGIN {\nuse Fcntl;\nuse File::Spec;\nmy $tempdir  = File::Spec->tmpdir();\nmy $filebase = sprintf \"%d-%d-0000\", $$, time;\nmy $basename = File::Spec->catfile($tempdir, $filebase);\n\nsub tempfile {\nmy $fh;\nmy $count = 0;\nuntil( defined(fileno($fh)) || $count++ > 100 ) {\n$basename =~ s/-(\\d+)$/\"-\" . (1 + $1)/e;\n# OEXCL is required for security reasons.\nsysopen $fh, $basename, OWRONLY|OEXCL|OCREAT;\n}\n\nif( defined fileno($fh) ) {\nreturn ($fh, $basename);\n}\nelse {\nreturn ();\n}\n}\n}\n"
                    },
                    {
                        "name": "How can I manipulate fixed-record-length files?",
                        "content": "The most efficient way is using pack() and unpack(). This is faster than using substr() when\ntaking many, many strings. It is slower for just a few.\n\nHere is a sample chunk of code to break up and put back together again some fixed-format\ninput lines, in this case from the output of a normal, Berkeley-style ps:\n\n# sample input line:\n#   15158 p5  T      0:00 perl /home/tchrist/scripts/now-what\nmy $PST = 'A6 A4 A7 A5 A*';\nopen my $ps, '-|', 'ps';\nprint scalar <$ps>;\nmy @fields = qw( pid tt stat time command );\nwhile (<$ps>) {\nmy %process;\n@process{@fields} = unpack($PST, $);\nfor my $field ( @fields ) {\nprint \"$field: <$process{$field}>\\n\";\n}\nprint 'line=', pack($PST, @process{@fields} ), \"\\n\";\n}\n\nWe've used a hash slice in order to easily handle the fields of each row.  Storing the keys\nin an array makes it easy to operate on them as a group or loop over them with \"for\". It also\navoids polluting the program with global variables and using symbolic references.\n"
                    },
                    {
                        "name": "How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines?",
                        "content": ""
                    },
                    {
                        "name": "How do I make an array of filehandles?",
                        "content": "As of perl5.6, open() autovivifies file and directory handles as references if you pass it an\nuninitialized scalar variable.  You can then pass these references just like any other\nscalar, and use them in the place of named handles.\n\nopen my    $fh, $filename;\n\nopen local $fh, $filename;\n\nprint $fh \"Hello World!\\n\";\n\nprocessfile( $fh );\n\nIf you like, you can store these filehandles in an array or a hash.  If you access them\ndirectly, they aren't simple scalars and you need to give \"print\" a little help by placing\nthe filehandle reference in braces. Perl can only figure it out on its own when the\nfilehandle reference is a simple scalar.\n\nmy @fhs = ( $fh1, $fh2, $fh3 );\n\nfor( $i = 0; $i <= $#fhs; $i++ ) {\nprint {$fhs[$i]} \"just another Perl answer, \\n\";\n}\n\nBefore perl5.6, you had to deal with various typeglob idioms which you may see in older code.\n\nopen FILE, \"> $filename\";\nprocesstypeglob(   *FILE );\nprocessreference( \\*FILE );\n\nsub processtypeglob  { local *FH = shift; print FH  \"Typeglob!\" }\nsub processreference { local $fh = shift; print $fh \"Reference!\" }\n\nIf you want to create many anonymous handles, you should check out the Symbol or IO::Handle\nmodules.\n"
                    },
                    {
                        "name": "How can I use a filehandle indirectly?",
                        "content": "An indirect filehandle is the use of something other than a symbol in a place that a\nfilehandle is expected. Here are ways to get indirect filehandles:\n\n$fh =   SOMEFH;       # bareword is strict-subs hostile\n$fh =  \"SOMEFH\";      # strict-refs hostile; same package only\n$fh =  *SOMEFH;       # typeglob\n$fh = \\*SOMEFH;       # ref to typeglob (bless-able)\n$fh =  *SOMEFH{IO};   # blessed IO::Handle from *SOMEFH typeglob\n\nOr, you can use the \"new\" method from one of the IO::* modules to create an anonymous\nfilehandle and store that in a scalar variable.\n\nuse IO::Handle;                     # 5.004 or higher\nmy $fh = IO::Handle->new();\n\nThen use any of those as you would a normal filehandle. Anywhere that Perl is expecting a\nfilehandle, an indirect filehandle may be used instead. An indirect filehandle is just a\nscalar variable that contains a filehandle. Functions like \"print\", \"open\", \"seek\", or the\n\"<FH>\" diamond operator will accept either a named filehandle or a scalar variable containing\none:\n\n($ifh, $ofh, $efh) = (*STDIN, *STDOUT, *STDERR);\nprint $ofh \"Type it: \";\nmy $got = <$ifh>\nprint $efh \"What was that: $got\";\n\nIf you're passing a filehandle to a function, you can write the function in two ways:\n\nsub acceptfh {\nmy $fh = shift;\nprint $fh \"Sending to indirect filehandle\\n\";\n}\n\nOr it can localize a typeglob and use the filehandle directly:\n\nsub acceptfh {\nlocal *FH = shift;\nprint  FH \"Sending to localized filehandle\\n\";\n}\n\nBoth styles work with either objects or typeglobs of real filehandles.  (They might also work\nwith strings under some circumstances, but this is risky.)\n\nacceptfh(*STDOUT);\nacceptfh($handle);\n\nIn the examples above, we assigned the filehandle to a scalar variable before using it. That\nis because only simple scalar variables, not expressions or subscripts of hashes or arrays,\ncan be used with built-ins like \"print\", \"printf\", or the diamond operator. Using something\nother than a simple scalar variable as a filehandle is illegal and won't even compile:\n\nmy @fd = (*STDIN, *STDOUT, *STDERR);\nprint $fd[1] \"Type it: \";                           # WRONG\nmy $got = <$fd[0]>                                  # WRONG\nprint $fd[2] \"What was that: $got\";                 # WRONG\n\nWith \"print\" and \"printf\", you get around this by using a block and an expression where you\nwould place the filehandle:\n\nprint  { $fd[1] } \"funny stuff\\n\";\nprintf { $fd[1] } \"Pity the poor %x.\\n\", 3735928559;\n# Pity the poor deadbeef.\n\nThat block is a proper block like any other, so you can put more complicated code there. This\nsends the message out to one of two places:\n\nmy $ok = -x \"/bin/cat\";\nprint { $ok ? $fd[1] : $fd[2] } \"cat stat $ok\\n\";\nprint { $fd[ 1+ ($ok || 0) ]  } \"cat stat $ok\\n\";\n\nThis approach of treating \"print\" and \"printf\" like object methods calls doesn't work for the\ndiamond operator. That's because it's a real operator, not just a function with a comma-less\nargument. Assuming you've been storing typeglobs in your structure as we did above, you can\nuse the built-in function named \"readline\" to read a record just as \"<>\" does. Given the\ninitialization shown above for @fd, this would work, but only because readline() requires a\ntypeglob. It doesn't work with objects or strings, which might be a bug we haven't fixed yet.\n\n$got = readline($fd[0]);\n\nLet it be noted that the flakiness of indirect filehandles is not related to whether they're\nstrings, typeglobs, objects, or anything else.  It's the syntax of the fundamental operators.\nPlaying the object game doesn't help you at all here.\n"
                    },
                    {
                        "name": "How can I open a filehandle to a string?",
                        "content": "(contributed by Peter J. Holzer, hjp-usenet2@hjp.at)\n\nSince Perl 5.8.0 a file handle referring to a string can be created by calling open with a\nreference to that string instead of the filename.  This file handle can then be used to read\nfrom or write to the string:\n\nopen(my $fh, '>', \\$string) or die \"Could not open string for writing\";\nprint $fh \"foo\\n\";\nprint $fh \"bar\\n\";    # $string now contains \"foo\\nbar\\n\"\n\nopen(my $fh, '<', \\$string) or die \"Could not open string for reading\";\nmy $x = <$fh>;    # $x now contains \"foo\\n\"\n\nWith older versions of Perl, the IO::String module provides similar functionality.\n"
                    },
                    {
                        "name": "How can I set up a footer format to be used with write()?",
                        "content": "There's no builtin way to do this, but perlform has a couple of techniques to make it\npossible for the intrepid hacker.\n"
                    },
                    {
                        "name": "How can I write() into a string?",
                        "content": "(contributed by brian d foy)\n\nIf you want to \"write\" into a string, you just have to <open> a filehandle to a string, which\nPerl has been able to do since Perl 5.6:\n\nopen FH, '>', \\my $string;\nwrite( FH );\n\nSince you want to be a good programmer, you probably want to use a lexical filehandle, even\nthough formats are designed to work with bareword filehandles since the default format names\ntake the filehandle name. However, you can control this with some Perl special per-filehandle\nvariables: $^, which names the top-of-page format, and $~ which shows the line format. You\nhave to change the default filehandle to set these variables:\n\nopen my($fh), '>', \\my $string;\n\n{ # set per-filehandle variables\nmy $oldfh = select( $fh );\n$~ = 'ANIMAL';\n$^ = 'ANIMALTOP';\nselect( $oldfh );\n}\n\nformat ANIMALTOP =\nID  Type    Name\n.\n\nformat ANIMAL =\n@##   @<<<    @<<<<<<<<<<<<<<\n$id,  $type,  $name\n.\n\nAlthough write can work with lexical or package variables, whatever variables you use have to\nscope in the format. That most likely means you'll want to localize some package variables:\n\n{\nlocal( $id, $type, $name ) = qw( 12 cat Buster );\nwrite( $fh );\n}\n\nprint $string;\n\nThere are also some tricks that you can play with \"formline\" and the accumulator variable\n$^A, but you lose a lot of the value of formats since \"formline\" won't handle paging and so\non. You end up reimplementing formats when you use them.\n"
                    },
                    {
                        "name": "How can I output my numbers with commas added?",
                        "content": "(contributed by brian d foy and Benjamin Goldberg)\n\nYou can use Number::Format to separate places in a number.  It handles locale information for\nthose of you who want to insert full stops instead (or anything else that they want to use,\nreally).\n\nThis subroutine will add commas to your number:\n\nsub commify {\nlocal $  = shift;\n1 while s/^([-+]?\\d+)(\\d{3})/$1,$2/;\nreturn $;\n}\n\nThis regex from Benjamin Goldberg will add commas to numbers:\n\ns/(^[-+]?\\d+?(?=(?>(?:\\d{3})+)(?!\\d))|\\G\\d{3}(?=\\d))/$1,/g;\n\nIt is easier to see with comments:\n\ns/(\n^[-+]?             # beginning of number.\n\\d+?               # first digits before first comma\n(?=                # followed by, (but not included in the match) :\n(?>(?:\\d{3})+) # some positive multiple of three digits.\n(?!\\d)         # an *exact* multiple, not x * 3 + 1 or whatever.\n)\n|                  # or:\n\\G\\d{3}            # after the last group, get three digits\n(?=\\d)             # but they have to have more digits after them.\n)/$1,/xg;\n"
                    },
                    {
                        "name": "How can I translate tildes (~) in a filename?",
                        "content": "Use the <> (\"glob()\") operator, documented in perlfunc.  Versions of Perl older than 5.6\nrequire that you have a shell installed that groks tildes. Later versions of Perl have this\nfeature built in. The File::KGlob module (available from CPAN) gives more portable glob\nfunctionality.\n\nWithin Perl, you may use this directly:\n\n$filename =~ s{\n^ ~             # find a leading tilde\n(               # save this in $1\n[^/]        # a non-slash character\n*     # repeated 0 or more times (0 means me)\n)\n}{\n$1\n? (getpwnam($1))[7]\n: ( $ENV{HOME} || $ENV{LOGDIR} )\n}ex;\n"
                    },
                    {
                        "name": "How come when I open a file read-write it wipes it out?",
                        "content": "Because you're using something like this, which truncates the file then gives you read-write\naccess:\n\nopen my $fh, '+>', '/path/name'; # WRONG (almost always)\n\nWhoops. You should instead use this, which will fail if the file doesn't exist:\n\nopen my $fh, '+<', '/path/name'; # open for update\n\nUsing \">\" always clobbers or creates. Using \"<\" never does either. The \"+\" doesn't change\nthis.\n\nHere are examples of many kinds of file opens. Those using \"sysopen\" all assume that you've\npulled in the constants from Fcntl:\n\nuse Fcntl;\n\nTo open file for reading:\n\nopen my $fh, '<', $path                               or die $!;\nsysopen my $fh, $path, ORDONLY                       or die $!;\n\nTo open file for writing, create new file if needed or else truncate old file:\n\nopen my $fh, '>', $path                               or die $!;\nsysopen my $fh, $path, OWRONLY|OTRUNC|OCREAT       or die $!;\nsysopen my $fh, $path, OWRONLY|OTRUNC|OCREAT, 0666 or die $!;\n\nTo open file for writing, create new file, file must not exist:\n\nsysopen my $fh, $path, OWRONLY|OEXCL|OCREAT        or die $!;\nsysopen my $fh, $path, OWRONLY|OEXCL|OCREAT, 0666  or die $!;\n\nTo open file for appending, create if necessary:\n\nopen my $fh, '>>', $path                              or die $!;\nsysopen my $fh, $path, OWRONLY|OAPPEND|OCREAT      or die $!;\nsysopen my $fh, $path, OWRONLY|OAPPEND|OCREAT, 0666 or die $!;\n\nTo open file for appending, file must exist:\n\nsysopen my $fh, $path, OWRONLY|OAPPEND              or die $!;\n\nTo open file for update, file must exist:\n\nopen my $fh, '+<', $path                              or die $!;\nsysopen my $fh, $path, ORDWR                         or die $!;\n\nTo open file for update, create file if necessary:\n\nsysopen my $fh, $path, ORDWR|OCREAT                 or die $!;\nsysopen my $fh, $path, ORDWR|OCREAT, 0666           or die $!;\n\nTo open file for update, file must not exist:\n\nsysopen my $fh, $path, ORDWR|OEXCL|OCREAT          or die $!;\nsysopen my $fh, $path, ORDWR|OEXCL|OCREAT, 0666    or die $!;\n\nTo open a file without blocking, creating if necessary:\n\nsysopen my $fh, '/foo/somefile', OWRONLY|ONDELAY|OCREAT\nor die \"can't open /foo/somefile: $!\":\n\nBe warned that neither creation nor deletion of files is guaranteed to be an atomic operation\nover NFS. That is, two processes might both successfully create or unlink the same file!\nTherefore OEXCL isn't as exclusive as you might wish.\n\nSee also perlopentut.\n\nWhy do I sometimes get an \"Argument list too long\" when I use <*>?\nThe \"<>\" operator performs a globbing operation (see above).  In Perl versions earlier than\nv5.6.0, the internal glob() operator forks csh(1) to do the actual glob expansion, but csh\ncan't handle more than 127 items and so gives the error message \"Argument list too long\".\nPeople who installed tcsh as csh won't have this problem, but their users may be surprised by\nit.\n\nTo get around this, either upgrade to Perl v5.6.0 or later, do the glob yourself with\nreaddir() and patterns, or use a module like File::Glob, one that doesn't use the shell to do\nglobbing.\n"
                    },
                    {
                        "name": "How can I open a file named with a leading \">\" or trailing blanks?",
                        "content": "(contributed by Brian McCauley)\n\nThe special two-argument form of Perl's open() function ignores trailing blanks in filenames\nand infers the mode from certain leading characters (or a trailing \"|\"). In older versions of\nPerl this was the only version of open() and so it is prevalent in old code and books.\n\nUnless you have a particular reason to use the two-argument form you should use the three-\nargument form of open() which does not treat any characters in the filename as special.\n\nopen my $fh, \"<\", \"  file  \";  # filename is \"   file   \"\nopen my $fh, \">\", \">file\";     # filename is \">file\"\n"
                    },
                    {
                        "name": "How can I reliably rename a file?",
                        "content": "If your operating system supports a proper mv(1) utility or its functional equivalent, this\nworks:\n\nrename($old, $new) or system(\"mv\", $old, $new);\n\nIt may be more portable to use the File::Copy module instead.  You just copy to the new file\nto the new name (checking return values), then delete the old one. This isn't really the same\nsemantically as a \"rename()\", which preserves meta-information like permissions, timestamps,\ninode info, etc.\n"
                    },
                    {
                        "name": "How can I lock a file?",
                        "content": "Perl's builtin flock() function (see perlfunc for details) will call flock(2) if that exists,\nfcntl(2) if it doesn't (on perl version 5.004 and later), and lockf(3) if neither of the two\nprevious system calls exists.  On some systems, it may even use a different form of native\nlocking.  Here are some gotchas with Perl's flock():\n\n1.  Produces a fatal error if none of the three system calls (or their close equivalent)\nexists.\n\n2.  lockf(3) does not provide shared locking, and requires that the filehandle be open for\nwriting (or appending, or read/writing).\n\n3.  Some versions of flock() can't lock files over a network (e.g. on NFS file systems), so\nyou'd need to force the use of fcntl(2) when you build Perl.  But even this is dubious at\nbest. See the flock entry of perlfunc and the INSTALL file in the source distribution for\ninformation on building Perl to do this.\n\nTwo potentially non-obvious but traditional flock semantics are that it waits\nindefinitely until the lock is granted, and that its locks are merely advisory. Such\ndiscretionary locks are more flexible, but offer fewer guarantees. This means that files\nlocked with flock() may be modified by programs that do not also use flock(). Cars that\nstop for red lights get on well with each other, but not with cars that don't stop for\nred lights. See the perlport manpage, your port's specific documentation, or your system-\nspecific local manpages for details. It's best to assume traditional behavior if you're\nwriting portable programs.  (If you're not, you should as always feel perfectly free to\nwrite for your own system's idiosyncrasies (sometimes called \"features\").  Slavish\nadherence to portability concerns shouldn't get in the way of your getting your job\ndone.)\n\nFor more information on file locking, see also \"File Locking\" in perlopentut if you have\nit (new for 5.6).\n"
                    },
                    {
                        "name": "Why can't I just open(FH, \">file.lock\")?",
                        "content": "A common bit of code NOT TO USE is this:\n\nsleep(3) while -e 'file.lock';    # PLEASE DO NOT USE\nopen my $lock, '>', 'file.lock'; # THIS BROKEN CODE\n\nThis is a classic race condition: you take two steps to do something which must be done in\none. That's why computer hardware provides an atomic test-and-set instruction. In theory,\nthis \"ought\" to work:\n\nsysopen my $fh, \"file.lock\", OWRONLY|OEXCL|OCREAT\nor die \"can't open  file.lock: $!\";\n\nexcept that lamentably, file creation (and deletion) is not atomic over NFS, so this won't\nwork (at least, not every time) over the net.  Various schemes involving link() have been\nsuggested, but these tend to involve busy-wait, which is also less than desirable.\n"
                    },
                    {
                        "name": "I still don't get locking. I just want to increment the number in the file. How can I do this?",
                        "content": "Didn't anyone ever tell you web-page hit counters were useless?  They don't count number of\nhits, they're a waste of time, and they serve only to stroke the writer's vanity. It's better\nto pick a random number; they're more realistic.\n\nAnyway, this is what you can do if you can't help yourself.\n\nuse Fcntl qw(:DEFAULT :flock);\nsysopen my $fh, \"numfile\", ORDWR|OCREAT or die \"can't open numfile: $!\";\nflock $fh, LOCKEX                        or die \"can't flock numfile: $!\";\nmy $num = <$fh> || 0;\nseek $fh, 0, 0                            or die \"can't rewind numfile: $!\";\ntruncate $fh, 0                           or die \"can't truncate numfile: $!\";\n(print $fh $num+1, \"\\n\")                  or die \"can't write numfile: $!\";\nclose $fh                                 or die \"can't close numfile: $!\";\n\nHere's a much better web-page hit counter:\n\n$hits = int( (time() - 850000000) / rand(1000) );\n\nIf the count doesn't impress your friends, then the code might. :-)\n"
                    },
                    {
                        "name": "All I want to do is append a small amount of text to the end of a file. Do I still have to use",
                        "content": ""
                    },
                    {
                        "name": "locking?",
                        "content": "If you are on a system that correctly implements \"flock\" and you use the example appending\ncode from \"perldoc -f flock\" everything will be OK even if the OS you are on doesn't\nimplement append mode correctly (if such a system exists). So if you are happy to restrict\nyourself to OSs that implement \"flock\" (and that's not really much of a restriction) then\nthat is what you should do.\n\nIf you know you are only going to use a system that does correctly implement appending (i.e.\nnot Win32) then you can omit the \"seek\" from the code in the previous answer.\n\nIf you know you are only writing code to run on an OS and filesystem that does implement\nappend mode correctly (a local filesystem on a modern Unix for example), and you keep the\nfile in block-buffered mode and you write less than one buffer-full of output between each\nmanual flushing of the buffer then each bufferload is almost guaranteed to be written to the\nend of the file in one chunk without getting intermingled with anyone else's output. You can\nalso use the \"syswrite\" function which is simply a wrapper around your system's write(2)\nsystem call.\n\nThere is still a small theoretical chance that a signal will interrupt the system-level\n\"write()\" operation before completion. There is also a possibility that some STDIO\nimplementations may call multiple system level \"write()\"s even if the buffer was empty to\nstart. There may be some systems where this probability is reduced to zero, and this is not a\nconcern when using \":perlio\" instead of your system's STDIO.\n"
                    },
                    {
                        "name": "How do I randomly update a binary file?",
                        "content": "If you're just trying to patch a binary, in many cases something as simple as this works:\n\nperl -i -pe 's{window manager}{window mangler}g' /usr/bin/emacs\n\nHowever, if you have fixed sized records, then you might do something more like this:\n\nmy $RECSIZE = 220; # size of record, in bytes\nmy $recno   = 37;  # which record to update\nopen my $fh, '+<', 'somewhere' or die \"can't update somewhere: $!\";\nseek $fh, $recno * $RECSIZE, 0;\nread $fh, $record, $RECSIZE == $RECSIZE or die \"can't read record $recno: $!\";\n# munge the record\nseek $fh, -$RECSIZE, 1;\nprint $fh $record;\nclose $fh;\n\nLocking and error checking are left as an exercise for the reader.  Don't forget them or\nyou'll be quite sorry.\n"
                    },
                    {
                        "name": "How do I get a file's timestamp in perl?",
                        "content": "If you want to retrieve the time at which the file was last read, written, or had its meta-\ndata (owner, etc) changed, you use the -A, -M, or -C file test operations as documented in\nperlfunc.  These retrieve the age of the file (measured against the start-time of your\nprogram) in days as a floating point number. Some platforms may not have all of these times.\nSee perlport for details. To retrieve the \"raw\" time in seconds since the epoch, you would\ncall the stat function, then use \"localtime()\", \"gmtime()\", or \"POSIX::strftime()\" to convert\nthis into human-readable form.\n\nHere's an example:\n\nmy $writesecs = (stat($file))[9];\nprintf \"file %s updated at %s\\n\", $file,\nscalar localtime($writesecs);\n\nIf you prefer something more legible, use the File::stat module (part of the standard\ndistribution in version 5.004 and later):\n\n# error checking left as an exercise for reader.\nuse File::stat;\nuse Time::localtime;\nmy $datestring = ctime(stat($file)->mtime);\nprint \"file $file updated at $datestring\\n\";\n\nThe POSIX::strftime() approach has the benefit of being, in theory, independent of the\ncurrent locale. See perllocale for details.\n"
                    },
                    {
                        "name": "How do I set a file's timestamp in perl?",
                        "content": "You use the utime() function documented in \"utime\" in perlfunc.  By way of example, here's a\nlittle program that copies the read and write times from its first argument to all the rest\nof them.\n\nif (@ARGV < 2) {\ndie \"usage: cptimes timestampfile otherfiles ...\\n\";\n}\nmy $timestamp = shift;\nmy($atime, $mtime) = (stat($timestamp))[8,9];\nutime $atime, $mtime, @ARGV;\n\nError checking is, as usual, left as an exercise for the reader.\n\nThe perldoc for utime also has an example that has the same effect as touch(1) on files that\nalready exist.\n\nCertain file systems have a limited ability to store the times on a file at the expected\nlevel of precision. For example, the FAT and HPFS filesystem are unable to create dates on\nfiles with a finer granularity than two seconds. This is a limitation of the filesystems, not\nof utime().\n"
                    },
                    {
                        "name": "How do I print to more than one file at once?",
                        "content": "To connect one filehandle to several output filehandles, you can use the IO::Tee or\nTie::FileHandle::Multiplex modules.\n\nIf you only have to do this once, you can print individually to each filehandle.\n\nfor my $fh ($fh1, $fh2, $fh3) { print $fh \"whatever\\n\" }\n"
                    },
                    {
                        "name": "How can I read in an entire file all at once?",
                        "content": "The customary Perl approach for processing all the lines in a file is to do so one line at a\ntime:\n\nopen my $input, '<', $file or die \"can't open $file: $!\";\nwhile (<$input>) {\nchomp;\n# do something with $\n}\nclose $input or die \"can't close $file: $!\";\n\nThis is tremendously more efficient than reading the entire file into memory as an array of\nlines and then processing it one element at a time, which is often--if not almost always--the\nwrong approach. Whenever you see someone do this:\n\nmy @lines = <INPUT>;\n\nYou should think long and hard about why you need everything loaded at once. It's just not a\nscalable solution.\n\nIf you \"mmap\" the file with the File::Map module from CPAN, you can virtually load the entire\nfile into a string without actually storing it in memory:\n\nuse File::Map qw(mapfile);\n\nmapfile my $string, $filename;\n\nOnce mapped, you can treat $string as you would any other string.  Since you don't\nnecessarily have to load the data, mmap-ing can be very fast and may not increase your memory\nfootprint.\n\nYou might also find it more fun to use the standard Tie::File module, or the DBFile module's\n$DBRECNO bindings, which allow you to tie an array to a file so that accessing an element of\nthe array actually accesses the corresponding line in the file.\n\nIf you want to load the entire file, you can use the Path::Tiny module to do it in one simple\nand efficient step:\n\nuse Path::Tiny;\n\nmy $allofit = path($filename)->slurp; # entire file in scalar\nmy @alllines = path($filename)->lines; # one line per element\n\nOr you can read the entire file contents into a scalar like this:\n\nmy $var;\n{\nlocal $/;\nopen my $fh, '<', $file or die \"can't open $file: $!\";\n$var = <$fh>;\n}\n\nThat temporarily undefs your record separator, and will automatically close the file at block\nexit. If the file is already open, just use this:\n\nmy $var = do { local $/; <$fh> };\n\nYou can also use a localized @ARGV to eliminate the \"open\":\n\nmy $var = do { local( @ARGV, $/ ) = $file; <> };\n\nFor ordinary files you can also use the \"read\" function.\n\nread( $fh, $var, -s $fh );\n\nThat third argument tests the byte size of the data on the $fh filehandle and reads that many\nbytes into the buffer $var.\n"
                    },
                    {
                        "name": "How can I read in a file by paragraphs?",
                        "content": "Use the $/ variable (see perlvar for details). You can either set it to \"\" to eliminate empty\nparagraphs (\"abc\\n\\n\\n\\ndef\", for instance, gets treated as two paragraphs and not three), or\n\"\\n\\n\" to accept empty paragraphs.\n\nNote that a blank line must have no blanks in it. Thus \"fred\\n \\nstuff\\n\\n\" is one paragraph,\nbut \"fred\\n\\nstuff\\n\\n\" is two.\n"
                    },
                    {
                        "name": "How can I read a single character from a file? From the keyboard?",
                        "content": "You can use the builtin \"getc()\" function for most filehandles, but it won't (easily) work on\na terminal device. For STDIN, either use the Term::ReadKey module from CPAN or use the sample\ncode in \"getc\" in perlfunc.\n\nIf your system supports the portable operating system programming interface (POSIX), you can\nuse the following code, which you'll note turns off echo processing as well.\n\n#!/usr/bin/perl -w\nuse strict;\n$| = 1;\nfor (1..4) {\nprint \"gimme: \";\nmy $got = getone();\nprint \"--> $got\\n\";\n}\nexit;\n\nBEGIN {\nuse POSIX qw(:termiosh);\n\nmy ($term, $oterm, $echo, $noecho, $fdstdin);\n\nmy $fdstdin = fileno(STDIN);\n\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);\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 getone {\nmy $key = '';\ncbreak();\nsysread(STDIN, $key, 1);\ncooked();\nreturn $key;\n}\n}\n\nEND { cooked() }\n\nThe Term::ReadKey module from CPAN may be easier to use. Recent versions include also support\nfor non-portable systems as well.\n\nuse Term::ReadKey;\nopen my $tty, '<', '/dev/tty';\nprint \"Gimme a char: \";\nReadMode \"raw\";\nmy $key = ReadKey 0, $tty;\nReadMode \"normal\";\nprintf \"\\nYou said %s, char number %03d\\n\",\n$key, ord $key;\n"
                    },
                    {
                        "name": "How can I tell whether there's a character waiting on a filehandle?",
                        "content": "The very first thing you should do is look into getting the Term::ReadKey extension from\nCPAN. As we mentioned earlier, it now even has limited support for non-portable (read: not\nopen systems, closed, proprietary, not POSIX, not Unix, etc.) systems.\n\nYou should also check out the Frequently Asked Questions list in comp.unix.* for things like\nthis: the answer is essentially the same.  It's very system-dependent. Here's one solution\nthat works on BSD systems:\n\nsub keyready {\nmy($rin, $nfd);\nvec($rin, fileno(STDIN), 1) = 1;\nreturn $nfd = select($rin,undef,undef,0);\n}\n\nIf you want to find out how many characters are waiting, there's also the FIONREAD ioctl call\nto be looked at. The h2ph tool that comes with Perl tries to convert C include files to Perl\ncode, which can be \"require\"d. FIONREAD ends up defined as a function in the sys/ioctl.ph\nfile:\n\nrequire './sys/ioctl.ph';\n\n$size = pack(\"L\", 0);\nioctl(FH, FIONREAD(), $size)    or die \"Couldn't call ioctl: $!\\n\";\n$size = unpack(\"L\", $size);\n\nIf h2ph wasn't installed or doesn't work for you, you can grep the include files by hand:\n\n% grep FIONREAD /usr/include/*/*\n/usr/include/asm/ioctls.h:#define FIONREAD      0x541B\n\nOr write a small C program using the editor of champions:\n\n% cat > fionread.c\n#include <sys/ioctl.h>\nmain() {\nprintf(\"%#08x\\n\", FIONREAD);\n}\n^D\n% cc -o fionread fionread.c\n% ./fionread\n0x4004667f\n\nAnd then hard-code it, leaving porting as an exercise to your successor.\n\n$FIONREAD = 0x4004667f;         # XXX: opsys dependent\n\n$size = pack(\"L\", 0);\nioctl(FH, $FIONREAD, $size)     or die \"Couldn't call ioctl: $!\\n\";\n$size = unpack(\"L\", $size);\n\nFIONREAD requires a filehandle connected to a stream, meaning that sockets, pipes, and tty\ndevices work, but not files.\n"
                    },
                    {
                        "name": "How do I do a \"tail -f\" in perl?",
                        "content": "First try\n\nseek($gwfh, 0, 1);\n\nThe statement \"seek($gwfh, 0, 1)\" doesn't change the current position, but it does clear the\nend-of-file condition on the handle, so that the next \"<$gwfh>\" makes Perl try again to read\nsomething.\n\nIf that doesn't work (it relies on features of your stdio implementation), then you need\nsomething more like this:\n\nfor (;;) {\nfor ($curpos = tell($gwfh); <$gwfh>; $curpos =tell($gwfh)) {\n# search for some stuff and put it into files\n}\n# sleep for a while\nseek($gwfh, $curpos, 0);  # seek to where we had been\n}\n\nIf this still doesn't work, look into the \"clearerr\" method from IO::Handle, which resets the\nerror and end-of-file states on the handle.\n\nThere's also a File::Tail module from CPAN.\n"
                    },
                    {
                        "name": "How do I dup() a filehandle in Perl?",
                        "content": "If you check \"open\" in perlfunc, you'll see that several of the ways to call open() should do\nthe trick. For example:\n\nopen my $log, '>>', '/foo/logfile';\nopen STDERR, '>&', $log;\n\nOr even with a literal numeric descriptor:\n\nmy $fd = $ENV{MHCONTEXTFD};\nopen $mhcontext, \"<&=$fd\";  # like fdopen(3S)\n\nNote that \"<&STDIN\" makes a copy, but \"<&=STDIN\" makes an alias. That means if you close an\naliased handle, all aliases become inaccessible. This is not true with a copied one.\n\nError checking, as always, has been left as an exercise for the reader.\n"
                    },
                    {
                        "name": "How do I close a file descriptor by number?",
                        "content": "If, for some reason, you have a file descriptor instead of a filehandle (perhaps you used\n\"POSIX::open\"), you can use the \"close()\" function from the POSIX module:\n\nuse POSIX ();\n\nPOSIX::close( $fd );\n\nThis should rarely be necessary, as the Perl \"close()\" function is to be used for things that\nPerl opened itself, even if it was a dup of a numeric descriptor as with \"MHCONTEXT\" above.\nBut if you really have to, you may be able to do this:\n\nrequire './sys/syscall.ph';\nmy $rc = syscall(SYSclose(), $fd + 0);  # must force numeric\ndie \"can't sysclose $fd: $!\" unless $rc == -1;\n\nOr, just use the fdopen(3S) feature of \"open()\":\n\n{\nopen my $fh, \"<&=$fd\" or die \"Cannot reopen fd=$fd: $!\";\nclose $fh;\n}\n"
                    },
                    {
                        "name": "Why can't I use \"C:\\temp\\foo\" in DOS paths? Why doesn't `C:\\temp\\foo.exe` work?",
                        "content": "Whoops!  You just put a tab and a formfeed into that filename!  Remember that within double\nquoted strings (\"like\\this\"), the backslash is an escape character. The full list of these is\nin \"Quote and Quote-like Operators\" in perlop. Unsurprisingly, you don't have a file called\n\"c:(tab)emp(formfeed)oo\" or \"c:(tab)emp(formfeed)oo.exe\" on your legacy DOS filesystem.\n\nEither single-quote your strings, or (preferably) use forward slashes.  Since all DOS and\nWindows versions since something like MS-DOS 2.0 or so have treated \"/\" and \"\\\" the same in a\npath, you might as well use the one that doesn't clash with Perl--or the POSIX shell, ANSI C\nand C++, awk, Tcl, Java, or Python, just to mention a few. POSIX paths are more portable,\ntoo.\n\nWhy doesn't glob(\"*.*\") get all the files?\nBecause even on non-Unix ports, Perl's glob function follows standard Unix globbing\nsemantics. You'll need \"glob(\"*\")\" to get all (non-hidden) files. This makes glob() portable\neven to legacy systems. Your port may include proprietary globbing functions as well. Check\nits documentation for details.\n"
                    },
                    {
                        "name": "Why does Perl let me delete read-only files? Why does \"-i\" clobber protected files? Isn't this a",
                        "content": ""
                    },
                    {
                        "name": "bug in Perl?",
                        "content": "This is elaborately and painstakingly described in the file-dir-perms article in the \"Far\nMore Than You Ever Wanted To Know\" collection in\n<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> .\n\nThe executive summary: learn how your filesystem works. The permissions on a file say what\ncan happen to the data in that file.  The permissions on a directory say what can happen to\nthe list of files in that directory. If you delete a file, you're removing its name from the\ndirectory (so the operation depends on the permissions of the directory, not of the file). If\nyou try to write to the file, the permissions of the file govern whether you're allowed to.\n"
                    },
                    {
                        "name": "How do I select a random line from a file?",
                        "content": "Short of loading the file into a database or pre-indexing the lines in the file, there are a\ncouple of things that you can do.\n\nHere's a reservoir-sampling algorithm from the Camel Book:\n\nsrand;\nrand($.) < 1 && ($line = $) while <>;\n\nThis has a significant advantage in space over reading the whole file in. You can find a\nproof of this method in The Art of Computer Programming, Volume 2, Section 3.4.2, by Donald\nE. Knuth.\n\nYou can use the File::Random module which provides a function for that algorithm:\n\nuse File::Random qw/randomline/;\nmy $line = randomline($filename);\n\nAnother way is to use the Tie::File module, which treats the entire file as an array. Simply\naccess a random array element.\n"
                    },
                    {
                        "name": "Why do I get weird spaces when I print an array of lines?",
                        "content": "(contributed by brian d foy)\n\nIf you are seeing spaces between the elements of your array when you print the array, you are\nprobably interpolating the array in double quotes:\n\nmy @animals = qw(camel llama alpaca vicuna);\nprint \"animals are: @animals\\n\";\n\nIt's the double quotes, not the \"print\", doing this. Whenever you interpolate an array in a\ndouble quote context, Perl joins the elements with spaces (or whatever is in $\", which is a\nspace by default):\n\nanimals are: camel llama alpaca vicuna\n\nThis is different than printing the array without the interpolation:\n\nmy @animals = qw(camel llama alpaca vicuna);\nprint \"animals are: \", @animals, \"\\n\";\n\nNow the output doesn't have the spaces between the elements because the elements of @animals\nsimply become part of the list to \"print\":\n\nanimals are: camelllamaalpacavicuna\n\nYou might notice this when each of the elements of @array end with a newline. You expect to\nprint one element per line, but notice that every line after the first is indented:\n\nthis is a line\nthis is another line\nthis is the third line\n\nThat extra space comes from the interpolation of the array. If you don't want to put anything\nbetween your array elements, don't use the array in double quotes. You can send it to print\nwithout them:\n\nprint @lines;\n"
                    },
                    {
                        "name": "How do I traverse a directory tree?",
                        "content": "(contributed by brian d foy)\n\nThe File::Find module, which comes with Perl, does all of the hard work to traverse a\ndirectory structure. It comes with Perl. You simply call the \"find\" subroutine with a\ncallback subroutine and the directories you want to traverse:\n\nuse File::Find;\n\nfind( \\&wanted, @directories );\n\nsub wanted {\n# full path in $File::Find::name\n# just filename in $\n... do whatever you want to do ...\n}\n\nThe File::Find::Closures, which you can download from CPAN, provides many ready-to-use\nsubroutines that you can use with File::Find.\n\nThe File::Finder, which you can download from CPAN, can help you create the callback\nsubroutine using something closer to the syntax of the \"find\" command-line utility:\n\nuse File::Find;\nuse File::Finder;\n\nmy $deepdirs = File::Finder->depth->type('d')->ls->exec('rmdir','{}');\n\nfind( $deepdirs->asoptions, @places );\n\nThe File::Find::Rule module, which you can download from CPAN, has a similar interface, but\ndoes the traversal for you too:\n\nuse File::Find::Rule;\n\nmy @files = File::Find::Rule->file()\n->name( '*.pm' )\n->in( @INC );\n"
                    },
                    {
                        "name": "How do I delete a directory tree?",
                        "content": "(contributed by brian d foy)\n\nIf you have an empty directory, you can use Perl's built-in \"rmdir\".  If the directory is not\nempty (so, with files or subdirectories), you either have to empty it yourself (a lot of\nwork) or use a module to help you.\n\nThe File::Path module, which comes with Perl, has a \"removetree\" which can take care of all\nof the hard work for you:\n\nuse File::Path qw(removetree);\n\nremovetree( @directories );\n\nThe File::Path module also has a legacy interface to the older \"rmtree\" subroutine.\n"
                    },
                    {
                        "name": "How do I copy an entire directory?",
                        "content": "(contributed by Shlomi Fish)\n\nTo do the equivalent of \"cp -R\" (i.e. copy an entire directory tree recursively) in portable\nPerl, you'll either need to write something yourself or find a good CPAN module such as\nFile::Copy::Recursive.\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 here are in the public domain. You are\npermitted and encouraged to use this code and any derivatives thereof in your own programs\nfor fun or for profit as you see fit. A simple comment in the code giving credit to the FAQ\nwould be courteous but is not required.\n\n\n\nperl v5.34.0                                 2025-07-25                                  PERLFAQ5(1)",
                "subsections": []
            }
        }
    }
}