{
    "content": [
        {
            "type": "text",
            "text": "# perlopentut (man)\n\n## NAME\n\nperlopentut - simple recipes for opening files and pipes in Perl\n\n## DESCRIPTION\n\nWhenever you do I/O on a file in Perl, you do so through what in Perl is called a filehandle.\nA filehandle is an internal name for an external file.  It is the job of the \"open\" function\nto make the association between the internal name and the external name, and it is the job of\nthe \"close\" function to break that association.\n\n## Sections\n\n- **NAME**\n- **DESCRIPTION** (8 subsections)\n- **SEE ALSO** (1 subsections)\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "perlopentut",
        "section": "",
        "mode": "man",
        "summary": "perlopentut - simple recipes for opening files and pipes in Perl",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 48,
                "subsections": [
                    {
                        "name": "Opening Text Files",
                        "lines": 1
                    },
                    {
                        "name": "Opening Text Files for Reading",
                        "lines": 63
                    },
                    {
                        "name": "Opening Text Files for Writing",
                        "lines": 40
                    },
                    {
                        "name": "Opening Binary Files",
                        "lines": 64
                    },
                    {
                        "name": "Opening Pipes",
                        "lines": 16
                    },
                    {
                        "name": "Opening a pipe for reading",
                        "lines": 32
                    },
                    {
                        "name": "Opening a pipe for writing",
                        "lines": 26
                    },
                    {
                        "name": "Expressing the command as a list",
                        "lines": 24
                    }
                ]
            },
            {
                "name": "SEE ALSO",
                "lines": 3,
                "subsections": [
                    {
                        "name": "AUTHOR and COPYRIGHT",
                        "lines": 8
                    }
                ]
            }
        ],
        "sections": {
            "NAME": {
                "content": "perlopentut - simple recipes for opening files and pipes in Perl\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "Whenever you do I/O on a file in Perl, you do so through what in Perl is called a filehandle.\nA filehandle is an internal name for an external file.  It is the job of the \"open\" function\nto make the association between the internal name and the external name, and it is the job of\nthe \"close\" function to break that association.\n\nFor your convenience, Perl sets up a few special filehandles that are already open when you\nrun.  These include \"STDIN\", \"STDOUT\", \"STDERR\", and \"ARGV\".  Since those are pre-opened, you\ncan use them right away without having to go to the trouble of opening them yourself:\n\nprint STDERR \"This is a debugging message.\\n\";\n\nprint STDOUT \"Please enter something: \";\n$response = <STDIN> // die \"how come no input?\";\nprint STDOUT \"Thank you!\\n\";\n\nwhile (<ARGV>) { ... }\n\nAs you see from those examples, \"STDOUT\" and \"STDERR\" are output handles, and \"STDIN\" and\n\"ARGV\" are input handles.  They are in all capital letters because they are reserved to Perl,\nmuch like the @ARGV array and the %ENV hash are.  Their external associations were set up by\nyour shell.\n\nYou will need to open every other filehandle on your own. Although there are many variants,\nthe most common way to call Perl's open() function is with three arguments and one return\nvalue:\n\n\"    OK = open(HANDLE, MODE, PATHNAME)\"\n\nWhere:\n\nOK  will be some defined value if the open succeeds, but \"undef\" if it fails;\n\nHANDLE\nshould be an undefined scalar variable to be filled in by the \"open\" function if it\nsucceeds;\n\nMODE\nis the access mode and the encoding format to open the file with;\n\nPATHNAME\nis the external name of the file you want opened.\n\nMost of the complexity of the \"open\" function lies in the many possible values that the MODE\nparameter can take on.\n\nOne last thing before we show you how to open files: opening files does not (usually)\nautomatically lock them in Perl.  See perlfaq5 for how to lock.\n",
                "subsections": [
                    {
                        "name": "Opening Text Files",
                        "content": ""
                    },
                    {
                        "name": "Opening Text Files for Reading",
                        "content": "If you want to read from a text file, first open it in read-only mode like this:\n\nmy $filename = \"/some/path/to/a/textfile/goes/here\";\nmy $encoding = \":encoding(UTF-8)\";\nmy $handle   = undef;     # this will be filled in on success\n\nopen($handle, \"< $encoding\", $filename)\n|| die \"$0: can't open $filename for reading: $!\";\n\nAs with the shell, in Perl the \"<\" is used to open the file in read-only mode.  If it\nsucceeds, Perl allocates a brand new filehandle for you and fills in your previously\nundefined $handle argument with a reference to that handle.\n\nNow you may use functions like \"readline\", \"read\", \"getc\", and \"sysread\" on that handle.\nProbably the most common input function is the one that looks like an operator:\n\n$line = readline($handle);\n$line = <$handle>;          # same thing\n\nBecause the \"readline\" function returns \"undef\" at end of file or upon error, you will\nsometimes see it used this way:\n\n$line = <$handle>;\nif (defined $line) {\n# do something with $line\n}\nelse {\n# $line is not valid, so skip it\n}\n\nYou can also just quickly \"die\" on an undefined value this way:\n\n$line = <$handle> // die \"no input found\";\n\nHowever, if hitting EOF is an expected and normal event, you do not want to exit simply\nbecause you have run out of input.  Instead, you probably just want to exit an input loop.\nYou can then test to see if an actual error has caused the loop to terminate, and act\naccordingly:\n\nwhile (<$handle>) {\n# do something with data in $\n}\nif ($!) {\ndie \"unexpected error while reading from $filename: $!\";\n}\n\nA Note on Encodings: Having to specify the text encoding every time might seem a bit of a\nbother.  To set up a default encoding for \"open\" so that you don't have to supply it each\ntime, you can use the \"open\" pragma:\n\nuse open qw< :encoding(UTF-8) >;\n\nOnce you've done that, you can safely omit the encoding part of the open mode:\n\nopen($handle, \"<\", $filename)\n|| die \"$0: can't open $filename for reading: $!\";\n\nBut never use the bare \"<\" without having set up a default encoding first.  Otherwise, Perl\ncannot know which of the many, many, many possible flavors of text file you have, and Perl\nwill have no idea how to correctly map the data in your file into actual characters it can\nwork with.  Other common encoding formats including \"ASCII\", \"ISO-8859-1\", \"ISO-8859-15\",\n\"Windows-1252\", \"MacRoman\", and even \"UTF-16LE\".  See perlunitut for more about encodings.\n"
                    },
                    {
                        "name": "Opening Text Files for Writing",
                        "content": "When you want to write to a file, you first have to decide what to do about any existing\ncontents of that file.  You have two basic choices here: to preserve or to clobber.\n\nIf you want to preserve any existing contents, then you want to open the file in append mode.\nAs in the shell, in Perl you use \">>\" to open an existing file in append mode.  \">>\" creates\nthe file if it does not already exist.\n\nmy $handle   = undef;\nmy $filename = \"/some/path/to/a/textfile/goes/here\";\nmy $encoding = \":encoding(UTF-8)\";\n\nopen($handle, \">> $encoding\", $filename)\n|| die \"$0: can't open $filename for appending: $!\";\n\nNow you can write to that filehandle using any of \"print\", \"printf\", \"say\", \"write\", or\n\"syswrite\".\n\nAs noted above, if the file does not already exist, then the append-mode open will create it\nfor you.  But if the file does already exist, its contents are safe from harm because you\nwill be adding your new text past the end of the old text.\n\nOn the other hand, sometimes you want to clobber whatever might already be there.  To empty\nout a file before you start writing to it, you can open it in write-only mode:\n\nmy $handle   = undef;\nmy $filename = \"/some/path/to/a/textfile/goes/here\";\nmy $encoding = \":encoding(UTF-8)\";\n\nopen($handle, \"> $encoding\", $filename)\n|| die \"$0: can't open $filename in write-open mode: $!\";\n\nHere again Perl works just like the shell in that the \">\" clobbers an existing file.\n\nAs with the append mode, when you open a file in write-only mode, you can now write to that\nfilehandle using any of \"print\", \"printf\", \"say\", \"write\", or \"syswrite\".\n\nWhat about read-write mode?  You should probably pretend it doesn't exist, because opening\ntext files in read-write mode is unlikely to do what you would like.  See perlfaq5 for\ndetails.\n"
                    },
                    {
                        "name": "Opening Binary Files",
                        "content": "If the file to be opened contains binary data instead of text characters, then the \"MODE\"\nargument to \"open\" is a little different.  Instead of specifying the encoding, you tell Perl\nthat your data are in raw bytes.\n\nmy $filename = \"/some/path/to/a/binary/file/goes/here\";\nmy $encoding = \":raw :bytes\"\nmy $handle   = undef;     # this will be filled in on success\n\nAnd then open as before, choosing \"<\", \">>\", or \">\" as needed:\n\nopen($handle, \"< $encoding\", $filename)\n|| die \"$0: can't open $filename for reading: $!\";\n\nopen($handle, \">> $encoding\", $filename)\n|| die \"$0: can't open $filename for appending: $!\";\n\nopen($handle, \"> $encoding\", $filename)\n|| die \"$0: can't open $filename in write-open mode: $!\";\n\nAlternately, you can change to binary mode on an existing handle this way:\n\nbinmode($handle)    || die \"cannot binmode handle\";\n\nThis is especially handy for the handles that Perl has already opened for you.\n\nbinmode(STDIN)      || die \"cannot binmode STDIN\";\nbinmode(STDOUT)     || die \"cannot binmode STDOUT\";\n\nYou can also pass \"binmode\" an explicit encoding to change it on the fly.  This isn't exactly\n\"binary\" mode, but we still use \"binmode\" to do it:\n\nbinmode(STDIN,  \":encoding(MacRoman)\") || die \"cannot binmode STDIN\";\nbinmode(STDOUT, \":encoding(UTF-8)\")    || die \"cannot binmode STDOUT\";\n\nOnce you have your binary file properly opened in the right mode, you can use all the same\nPerl I/O functions as you used on text files.  However, you may wish to use the fixed-size\n\"read\" instead of the variable-sized \"readline\" for your input.\n\nHere's an example of how to copy a binary file:\n\nmy $BUFSIZ   = 64 * (2  10);\nmy $namein  = \"/some/input/file\";\nmy $nameout = \"/some/output/flie\";\n\nmy($infh, $outfh, $buffer);\n\nopen($infh,  \"<\", $namein)\n|| die \"$0: cannot open $namein for reading: $!\";\nopen($outfh, \">\", $nameout)\n|| die \"$0: cannot open $nameout for writing: $!\";\n\nfor my $fh ($infh, $outfh)  {\nbinmode($fh)               || die \"binmode failed\";\n}\n\nwhile (read($infh, $buffer, $BUFSIZ)) {\nunless (print $outfh $buffer) {\ndie \"couldn't write to $nameout: $!\";\n}\n}\n\nclose($infh)       || die \"couldn't close $namein: $!\";\nclose($outfh)      || die \"couldn't close $nameout: $!\";\n"
                    },
                    {
                        "name": "Opening Pipes",
                        "content": "Perl also lets you open a filehandle into an external program or shell command rather than\ninto a file. You can do this in order to pass data from your Perl program to an external\ncommand for further processing, or to receive data from another program for your own Perl\nprogram to process.\n\nFilehandles into commands are also known as pipes, since they work on similar inter-process\ncommunication principles as Unix pipelines. Such a filehandle has an active program instead\nof a static file on its external end, but in every other sense it works just like a more\ntypical file-based filehandle, with all the techniques discussed earlier in this article just\nas applicable.\n\nAs such, you open a pipe using the same \"open\" call that you use for opening files, setting\nthe second (\"MODE\") argument to special characters that indicate either an input or an output\npipe. Use \"-|\" for a filehandle that will let your Perl program read data from an external\nprogram, and \"|-\" for a filehandle that will send data to that program instead.\n"
                    },
                    {
                        "name": "Opening a pipe for reading",
                        "content": "Let's say you'd like your Perl program to process data stored in a nearby directory called\n\"unsorted\", which contains a number of textfiles.  You'd also like your program to sort all\nthe contents from these files into a single, alphabetically sorted list of unique lines\nbefore it starts processing them.\n\nYou could do this through opening an ordinary filehandle into each of those files, gradually\nbuilding up an in-memory array of all the file contents you load this way, and finally\nsorting and filtering that array when you've run out of files to load. Or, you could offload\nall that merging and sorting into your operating system's own \"sort\" command by opening a\npipe directly into its output, and get to work that much faster.\n\nHere's how that might look:\n\nopen(my $sortfh, '-|', 'sort -u unsorted/*.txt')\nor die \"Couldn't open a pipe into sort: $!\";\n\n# And right away, we can start reading sorted lines:\nwhile (my $line = <$sortfh>) {\n#\n# ... Do something interesting with each $line here ...\n#\n}\n\nThe second argument to \"open\", \"-|\", makes it a read-pipe into a separate program, rather\nthan an ordinary filehandle into a file.\n\nNote that the third argument to \"open\" is a string containing the program name (\"sort\") plus\nall its arguments: in this case, \"-u\" to specify unqiue sort, and then a fileglob specifying\nthe files to sort.  The resulting filehandle $sortfh works just like a read-only (\"<\")\nfilehandle, and your program can subsequently read data from it as if it were opened onto an\nordinary, single file.\n"
                    },
                    {
                        "name": "Opening a pipe for writing",
                        "content": "Continuing the previous example, let's say that your program has completed its processing,\nand the results sit in an array called @processed. You want to print these lines to a file\ncalled \"numbered.txt\" with a neatly formatted column of line-numbers.\n\nCertainly you could write your own code to do this — or, once again, you could kick that work\nover to another program. In this case, \"cat\", running with its own \"-n\" option to activate\nline numbering, should do the trick:\n\nopen(my $catfh, '|-', 'cat -n > numbered.txt')\nor die \"Couldn't open a pipe into cat: $!\";\n\nfor my $line (@processed) {\nprint $catfh $line;\n}\n\nHere, we use a second \"open\" argument of \"|-\", signifying that the filehandle assigned to\n$catfh should be a write-pipe. We can then use it just as we would a write-only ordinary\nfilehandle, including the basic function of \"print\"-ing data to it.\n\nNote that the third argument, specifying the command that we wish to pipe to, sets up \"cat\"\nto redirect its output via that \">\" symbol into the file \"numbered.txt\". This can start to\nlook a little tricky, because that same symbol would have meant something entirely different\nhad it showed it in the second argument to \"open\"!  But here in the third argument, it's\nsimply part of the shell command that Perl will open the pipe into, and Perl itself doesn't\ninvest any special meaning to it.\n"
                    },
                    {
                        "name": "Expressing the command as a list",
                        "content": "For opening pipes, Perl offers the option to call \"open\" with a list comprising the desired\ncommand and all its own arguments as separate elements, rather than combining them into a\nsingle string as in the examples above. For instance, we could have phrased the \"open\" call\nin the first example like this:\n\nopen(my $sortfh, '-|', 'sort', '-u', glob('unsorted/*.txt'))\nor die \"Couldn't open a pipe into sort: $!\";\n\nWhen you call \"open\" this way, Perl invokes the given command directly, bypassing the shell.\nAs such, the shell won't try to interpret any special characters within the command's\nargument list, which might overwise have unwanted effects. This can make for safer, less\nerror-prone \"open\" calls, useful in cases such as passing in variables as arguments, or even\njust referring to filenames with spaces in them.\n\nHowever, when you do want to pass a meaningful metacharacter to the shell, such with the \"*\"\ninside that final \"unsorted/*.txt\" argument here, you can't use this alternate syntax. In\nthis case, we have worked around it via Perl's handy \"glob\" built-in function, which\nevaluates its argument into a list of filenames — and we can safely pass that resulting list\nright into \"open\", as shown above.\n\nNote also that representing piped-command arguments in list form like this doesn't work on\nevery platform. It will work on any Unix-based OS that provides a real \"fork\" function (e.g.\nmacOS or Linux), as well as on Windows when running Perl 5.22 or later.\n"
                    }
                ]
            },
            "SEE ALSO": {
                "content": "The full documentation for \"open\" provides a thorough reference to this function, beyond the\nbest-practice basics covered here.\n",
                "subsections": [
                    {
                        "name": "AUTHOR and COPYRIGHT",
                        "content": "Copyright 2013 Tom Christiansen; now maintained by Perl5 Porters\n\nThis documentation is free; you can redistribute it and/or modify it under the same terms as\nPerl itself.\n\n\n\nperl v5.34.0                                 2025-07-25                               PERLOPENTUT(1)"
                    }
                ]
            }
        }
    }
}