{
    "mode": "perldoc",
    "parameter": "Tie::File",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Tie%3A%3AFile/json",
    "generated": "2026-08-16T11:21:51Z",
    "synopsis": "use Tie::File;\ntie @array, 'Tie::File', filename or die ...;\n$array[0] = 'blah';      # first line of the file is now 'blah'\n# (line numbering starts at 0)\nprint $array[42];        # display line 43 of the file\n$nrecs = @array;        # how many records are in the file?\n$#array -= 2;            # chop two records off the end\nfor (@array) {\ns/PERL/Perl/g;        # Replace PERL with Perl everywhere in the file\n}\n# These are just like regular push, pop, unshift, shift, and splice\n# Except that they modify the file in the way you would expect\npush @array, new recs...;\nmy $r1 = pop @array;\nunshift @array, new recs...;\nmy $r2 = shift @array;\n@oldrecs = splice @array, 3, 7, new recs...;\nuntie @array;            # all finished",
    "sections": {
        "NAME": {
            "content": "Tie::File - Access the lines of a disk file via a Perl array\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use Tie::File;\n\ntie @array, 'Tie::File', filename or die ...;\n\n$array[0] = 'blah';      # first line of the file is now 'blah'\n# (line numbering starts at 0)\nprint $array[42];        # display line 43 of the file\n\n$nrecs = @array;        # how many records are in the file?\n$#array -= 2;            # chop two records off the end\n\n\nfor (@array) {\ns/PERL/Perl/g;        # Replace PERL with Perl everywhere in the file\n}\n\n# These are just like regular push, pop, unshift, shift, and splice\n# Except that they modify the file in the way you would expect\n\npush @array, new recs...;\nmy $r1 = pop @array;\nunshift @array, new recs...;\nmy $r2 = shift @array;\n@oldrecs = splice @array, 3, 7, new recs...;\n\nuntie @array;            # all finished\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "\"Tie::File\" represents a regular text file as a Perl array. Each element in the array\ncorresponds to a record in the file. The first line of the file is element 0 of the array; the\nsecond line is element 1, and so on.\n\nThe file is *not* loaded into memory, so this will work even for gigantic files.\n\nChanges to the array are reflected in the file immediately.\n\nLazy people and beginners may now stop reading the manual.\n\n\"recsep\"\nWhat is a 'record'? By default, the meaning is the same as for the \"<...>\" operator: It's a\nstring terminated by $/, which is probably \"\\n\". (Minor exception: on DOS and Win32 systems, a\n'record' is a string terminated by \"\\r\\n\".) You may change the definition of \"record\" by\nsupplying the \"recsep\" option in the \"tie\" call:\n\ntie @array, 'Tie::File', $file, recsep => 'es';\n\nThis says that records are delimited by the string \"es\". If the file contained the following\ndata:\n\nCurse these pesky flies!\\n\n\nthen the @array would appear to have four elements:\n\n\"Curse th\"\n\"e p\"\n\"ky fli\"\n\"!\\n\"\n\nAn undefined value is not permitted as a record separator. Perl's special \"paragraph mode\"\nsemantics (à la \"$/ = \"\"\") are not emulated.\n\nRecords read from the tied array do not have the record separator string on the end; this is to\nallow\n\n$array[17] .= \"extra\";\n\nto work as expected.\n\n(See \"autochomp\", below.) Records stored into the array will have the record separator string\nappended before they are written to the file, if they don't have one already. For example, if\nthe record separator string is \"\\n\", then the following two lines do exactly the same thing:\n\n$array[17] = \"Cherry pie\";\n$array[17] = \"Cherry pie\\n\";\n\nThe result is that the contents of line 17 of the file will be replaced with \"Cherry pie\"; a\nnewline character will separate line 17 from line 18. This means that this code will do nothing:\n\nchomp $array[17];\n\nBecause the \"chomp\"ed value will have the separator reattached when it is written back to the\nfile. There is no way to create a file whose trailing record separator string is missing.\n\nInserting records that *contain* the record separator string is not supported by this module. It\nwill probably produce a reasonable result, but what this result will be may change in a future\nversion. Use 'splice' to insert records or to replace one record with several.\n\n\"autochomp\"\nNormally, array elements have the record separator removed, so that if the file contains the\ntext\n\nGold\nFrankincense\nMyrrh\n\nthe tied array will appear to contain \"(\"Gold\", \"Frankincense\", \"Myrrh\")\". If you set\n\"autochomp\" to a false value, the record separator will not be removed. If the file above was\ntied with\n\ntie @gifts, \"Tie::File\", $gifts, autochomp => 0;\n\nthen the array @gifts would appear to contain \"(\"Gold\\n\", \"Frankincense\\n\", \"Myrrh\\n\")\", or (on\nWin32 systems) \"(\"Gold\\r\\n\", \"Frankincense\\r\\n\", \"Myrrh\\r\\n\")\".\n\n\"mode\"\nNormally, the specified file will be opened for read and write access, and will be created if it\ndoes not exist. (That is, the flags \"ORDWR | OCREAT\" are supplied in the \"open\" call.) If you\nwant to change this, you may supply alternative flags in the \"mode\" option. See Fcntl for a\nlisting of available flags. For example:\n\n# open the file if it exists, but fail if it does not exist\nuse Fcntl 'ORDWR';\ntie @array, 'Tie::File', $file, mode => ORDWR;\n\n# create the file if it does not exist\nuse Fcntl 'ORDWR', 'OCREAT';\ntie @array, 'Tie::File', $file, mode => ORDWR | OCREAT;\n\n# open an existing file in read-only mode\nuse Fcntl 'ORDONLY';\ntie @array, 'Tie::File', $file, mode => ORDONLY;\n\nOpening the data file in write-only or append mode is not supported.\n\n\"memory\"\nThis is an upper limit on the amount of memory that \"Tie::File\" will consume at any time while\nmanaging the file. This is used for two things: managing the *read cache* and managing the\n*deferred write buffer*.\n\nRecords read in from the file are cached, to avoid having to re-read them repeatedly. If you\nread the same record twice, the first time it will be stored in memory, and the second time it\nwill be fetched from the *read cache*. The amount of data in the read cache will not exceed the\nvalue you specified for \"memory\". If \"Tie::File\" wants to cache a new record, but the read cache\nis full, it will make room by expiring the least-recently visited records from the read cache.\n\nThe default memory limit is 2Mib. You can adjust the maximum read cache size by supplying the\n\"memory\" option. The argument is the desired cache size, in bytes.\n\n# I have a lot of memory, so use a large cache to speed up access\ntie @array, 'Tie::File', $file, memory => 20000000;\n\nSetting the memory limit to 0 will inhibit caching; records will be fetched from disk every time\nyou examine them.\n\nThe \"memory\" value is not an absolute or exact limit on the memory used. \"Tie::File\" objects\ncontains some structures besides the read cache and the deferred write buffer, whose sizes are\nnot charged against \"memory\".\n\nThe cache itself consumes about 310 bytes per cached record, so if your file has many short\nrecords, you may want to decrease the cache memory limit, or else the cache overhead may exceed\nthe size of the cached data.\n\n\"dwsize\"\n(This is an advanced feature. Skip this section on first reading.)\n\nIf you use deferred writing (See \"Deferred Writing\", below) then data you write into the array\nwill not be written directly to the file; instead, it will be saved in the *deferred write\nbuffer* to be written out later. Data in the deferred write buffer is also charged against the\nmemory limit you set with the \"memory\" option.\n\nYou may set the \"dwsize\" option to limit the amount of data that can be saved in the deferred\nwrite buffer. This limit may not exceed the total memory limit. For example, if you set\n\"dwsize\" to 1000 and \"memory\" to 2500, that means that no more than 1000 bytes of deferred\nwrites will be saved up. The space available for the read cache will vary, but it will always be\nat least 1500 bytes (if the deferred write buffer is full) and it could grow as large as 2500\nbytes (if the deferred write buffer is empty.)\n\nIf you don't specify a \"dwsize\", it defaults to the entire memory limit.\n",
            "subsections": [
                {
                    "name": "Option Format",
                    "content": "\"-mode\" is a synonym for \"mode\". \"-recsep\" is a synonym for \"recsep\". \"-memory\" is a synonym for\n\"memory\". You get the idea.\n"
                }
            ]
        },
        "Public Methods": {
            "content": "The \"tie\" call returns an object, say $o. You may call\n\n$rec = $o->FETCH($n);\n$o->STORE($n, $rec);\n\nto fetch or store the record at line $n, respectively; similarly the other tied array methods.\n(See perltie for details.) You may also call the following methods on this object:\n\n\"flock\"\n$o->flock(MODE)\n\nwill lock the tied file. \"MODE\" has the same meaning as the second argument to the Perl built-in\n\"flock\" function; for example \"LOCKSH\" or \"LOCKEX | LOCKNB\". (These constants are provided by\nthe \"use Fcntl ':flock'\" declaration.)\n\n\"MODE\" is optional; the default is \"LOCKEX\".\n\n\"Tie::File\" maintains an internal table of the byte offset of each record it has seen in the\nfile.\n\nWhen you use \"flock\" to lock the file, \"Tie::File\" assumes that the read cache is no longer\ntrustworthy, because another process might have modified the file since the last time it was\nread. Therefore, a successful call to \"flock\" discards the contents of the read cache and the\ninternal record offset table.\n\n\"Tie::File\" promises that the following sequence of operations will be safe:\n\nmy $o = tie @array, \"Tie::File\", $filename;\n$o->flock;\n\nIn particular, \"Tie::File\" will *not* read or write the file during the \"tie\" call. (Exception:\nUsing \"mode => OTRUNC\" will, of course, erase the file during the \"tie\" call. If you want to do\nthis safely, then open the file without \"OTRUNC\", lock the file, and use \"@array = ()\".)\n\nThe best way to unlock a file is to discard the object and untie the array. It is probably\nunsafe to unlock the file without also untying it, because if you do, changes may remain\nunwritten inside the object. That is why there is no shortcut for unlocking. If you really want\nto unlock the file prematurely, you know what to do; if you don't know what to do, then don't do\nit.\n\nAll the usual warnings about file locking apply here. In particular, note that file locking in\nPerl is advisory, which means that holding a lock will not prevent anyone else from reading,\nwriting, or erasing the file; it only prevents them from getting another lock at the same time.\nLocks are analogous to green traffic lights: If you have a green light, that does not prevent\nthe idiot coming the other way from plowing into you sideways; it merely guarantees to you that\nthe idiot does not also have a green light at the same time.\n\n\"autochomp\"\nmy $oldvalue = $o->autochomp(0);    # disable autochomp option\nmy $oldvalue = $o->autochomp(1);    #  enable autochomp option\n\nmy $ac = $o->autochomp();   # recover current value\n\nSee \"autochomp\", above.\n\n\"defer\", \"flush\", \"discard\", and \"autodefer\"\nSee \"Deferred Writing\", below.\n\n\"offset\"\n$off = $o->offset($n);\n\nThis method returns the byte offset of the start of the $nth record in the file. If there is no\nsuch record, it returns an undefined value.\n",
            "subsections": []
        },
        "Tying to an already-opened filehandle": {
            "content": "If $fh is a filehandle, such as is returned by \"IO::File\" or one of the other \"IO\" modules, you\nmay use:\n\ntie @array, 'Tie::File', $fh, ...;\n\nSimilarly if you opened that handle \"FH\" with regular \"open\" or \"sysopen\", you may use:\n\ntie @array, 'Tie::File', \\*FH, ...;\n\nHandles that were opened write-only won't work. Handles that were opened read-only will work as\nlong as you don't try to modify the array. Handles must be attached to seekable sources of\ndata---that means no pipes or sockets. If \"Tie::File\" can detect that you supplied a\nnon-seekable handle, the \"tie\" call will throw an exception. (On Unix systems, it can detect\nthis.)\n\nNote that Tie::File will only close any filehandles that it opened internally. If you passed it\na filehandle as above, you \"own\" the filehandle, and are responsible for closing it after you\nhave untied the @array.\n\nTie::File calls \"binmode\" on filehandles that it opens internally, but not on filehandles passed\nin by the user. For consistency, especially if using the tied files cross-platform, you may wish\nto call \"binmode\" on the filehandle prior to tying the file.\n",
            "subsections": []
        },
        "Deferred Writing": {
            "content": "(This is an advanced feature. Skip this section on first reading.)\n\nNormally, modifying a \"Tie::File\" array writes to the underlying file immediately. Every\nassignment like \"$a[3] = ...\" rewrites as much of the file as is necessary; typically,\neverything from line 3 through the end will need to be rewritten. This is the simplest and most\ntransparent behavior. Performance even for large files is reasonably good.\n\nHowever, under some circumstances, this behavior may be excessively slow. For example, suppose\nyou have a million-record file, and you want to do:\n\nfor (@FILE) {\n$ = \"> $\";\n}\n\nThe first time through the loop, you will rewrite the entire file, from line 0 through the end.\nThe second time through the loop, you will rewrite the entire file from line 1 through the end.\nThe third time through the loop, you will rewrite the entire file from line 2 to the end. And so\non.\n\nIf the performance in such cases is unacceptable, you may defer the actual writing, and then\nhave it done all at once. The following loop will perform much better for large files:\n\n(tied @a)->defer;\nfor (@a) {\n$ = \"> $\";\n}\n(tied @a)->flush;\n\nIf \"Tie::File\"'s memory limit is large enough, all the writing will done in memory. Then, when\nyou call \"->flush\", the entire file will be rewritten in a single pass.\n\n(Actually, the preceding discussion is something of a fib. You don't need to enable deferred\nwriting to get good performance for this common case, because \"Tie::File\" will do it for you\nautomatically unless you specifically tell it not to. See \"Autodeferring\", below.)\n\nCalling \"->flush\" returns the array to immediate-write mode. If you wish to discard the deferred\nwrites, you may call \"->discard\" instead of \"->flush\". Note that in some cases, some of the data\nwill have been written already, and it will be too late for \"->discard\" to discard all the\nchanges. Support for \"->discard\" may be withdrawn in a future version of \"Tie::File\".\n\nDeferred writes are cached in memory up to the limit specified by the \"dwsize\" option (see\nabove). If the deferred-write buffer is full and you try to write still more deferred data, the\nbuffer will be flushed. All buffered data will be written immediately, the buffer will be\nemptied, and the now-empty space will be used for future deferred writes.\n\nIf the deferred-write buffer isn't yet full, but the total size of the buffer and the read cache\nwould exceed the \"memory\" limit, the oldest records will be expired from the read cache until\nthe total size is under the limit.\n\n\"push\", \"pop\", \"shift\", \"unshift\", and \"splice\" cannot be deferred. When you perform one of\nthese operations, any deferred data is written to the file and the operation is performed\nimmediately. This may change in a future version.\n\nIf you resize the array with deferred writing enabled, the file will be resized immediately, but\ndeferred records will not be written. This has a surprising consequence: \"@a = (...)\" erases the\nfile immediately, but the writing of the actual data is deferred. This might be a bug. If it is\na bug, it will be fixed in a future version.\n",
            "subsections": [
                {
                    "name": "Autodeferring",
                    "content": "\"Tie::File\" tries to guess when deferred writing might be helpful, and to turn it on and off\nautomatically.\n\nfor (@a) {\n$ = \"> $\";\n}\n\nIn this example, only the first two assignments will be done immediately; after this, all the\nchanges to the file will be deferred up to the user-specified memory limit.\n\nYou should usually be able to ignore this and just use the module without thinking about\ndeferring. However, special applications may require fine control over which writes are\ndeferred, or may require that all writes be immediate. To disable the autodeferment feature, use\n\n(tied @o)->autodefer(0);\n\nor\n\ntie @array, 'Tie::File', $file, autodefer => 0;\n\nSimilarly, \"->autodefer(1)\" re-enables autodeferment, and \"->autodefer()\" recovers the current\nvalue of the autodefer setting.\n"
                }
            ]
        },
        "CONCURRENT ACCESS TO FILES": {
            "content": "Caching and deferred writing are inappropriate if you want the same file to be accessed\nsimultaneously from more than one process. Other optimizations performed internally by this\nmodule are also incompatible with concurrent access. A future version of this module will\nsupport a \"concurrent => 1\" option that enables safe concurrent access.\n\nPrevious versions of this documentation suggested using \"memory => 0\" for safe concurrent\naccess. This was mistaken. Tie::File will not support safe concurrent access before version\n0.96.\n",
            "subsections": []
        },
        "CAVEATS": {
            "content": "(That's Latin for 'warnings'.)\n\n*   Reasonable effort was made to make this module efficient. Nevertheless, changing the size of\na record in the middle of a large file will always be fairly slow, because everything after\nthe new record must be moved.\n\n*   The behavior of tied arrays is not precisely the same as for regular arrays. For example:\n\n# This DOES print \"How unusual!\"\nundef $a[10];  print \"How unusual!\\n\" if defined $a[10];\n\n\"undef\"-ing a \"Tie::File\" array element just blanks out the corresponding record in the\nfile. When you read it back again, you'll get the empty string, so the supposedly-\"undef\"'ed\nvalue will be defined. Similarly, if you have \"autochomp\" disabled, then\n\n# This DOES print \"How unusual!\" if 'autochomp' is disabled\nundef $a[10];\nprint \"How unusual!\\n\" if $a[10];\n\nBecause when \"autochomp\" is disabled, $a[10] will read back as \"\\n\" (or whatever the record\nseparator string is.)\n\nThere are other minor differences, particularly regarding \"exists\" and \"delete\", but in\ngeneral, the correspondence is extremely close.\n\n*   I have supposed that since this module is concerned with file I/O, almost all normal use of\nit will be heavily I/O bound. This means that the time to maintain complicated data\nstructures inside the module will be dominated by the time to actually perform the I/O. When\nthere was an opportunity to spend CPU time to avoid doing I/O, I usually tried to take it.\n\n*   You might be tempted to think that deferred writing is like transactions, with \"flush\" as\n\"commit\" and \"discard\" as \"rollback\", but it isn't, so don't.\n\n*   There is a large memory overhead for each record offset and for each cache entry: about 310\nbytes per cached data record, and about 21 bytes per offset table entry.\n\nThe per-record overhead will limit the maximum number of records you can access per file.\nNote that *accessing* the length of the array via \"$x = scalar @tiedfile\" accesses all\nrecords and stores their offsets. The same for \"foreach (@tiedfile)\", even if you exit the\nloop early.\n",
            "subsections": []
        },
        "SUBCLASSING": {
            "content": "This version promises absolutely nothing about the internals, which may change without notice. A\nfuture version of the module will have a well-defined and stable subclassing API.\n\nWHAT ABOUT \"DBFile\"?\nPeople sometimes point out that DBFile will do something similar, and ask why \"Tie::File\"\nmodule is necessary.\n\nThere are a number of reasons that you might prefer \"Tie::File\". A list is available at\n\"<http://perl.plover.com/TieFile/why-not-DBFile>\".\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Mark Jason Dominus\n\nTo contact the author, send email to: \"mjd-perl-tiefile+@plover.com\"\n\nTo receive an announcement whenever a new version of this module is released, send a blank email\nmessage to \"mjd-perl-tiefile-subscribe@plover.com\".\n\nThe most recent version of this module, including documentation and any news of importance, will\nbe available at\n\nhttp://perl.plover.com/TieFile/\n",
            "subsections": []
        },
        "LICENSE": {
            "content": "\"Tie::File\" version 0.96 is copyright (C) 2003 Mark Jason Dominus.\n\nThis library is free software; you may redistribute it and/or modify it under the same terms as\nPerl itself.\n\nThese terms are your choice of any of (1) the Perl Artistic Licence, or (2) version 2 of the GNU\nGeneral Public License as published by the Free Software Foundation, or (3) any later version of\nthe GNU General Public License.\n\nThis library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\nwithout even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See\nthe GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with this library\nprogram; it should be in the file \"COPYING\". If not, write to the Free Software Foundation,\nInc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n\nFor licensing inquiries, contact the author at:\n\nMark Jason Dominus\n255 S. Warnock St.\nPhiladelphia, PA 19107\n",
            "subsections": []
        },
        "WARRANTY": {
            "content": "\"Tie::File\" version 0.98 comes with ABSOLUTELY NO WARRANTY. For details, see the license.\n",
            "subsections": []
        },
        "THANKS": {
            "content": "Gigantic thanks to Jarkko Hietaniemi, for agreeing to put this in the core when I hadn't written\nit yet, and for generally being helpful, supportive, and competent. (Usually the rule is \"choose\nany one.\") Also big thanks to Abhijit Menon-Sen for all of the same things.\n\nSpecial thanks to Craig Berry and Peter Prymmer (for VMS portability help), Randy Kobes (for\nWin32 portability help), Clinton Pierce and Autrijus Tang (for heroic eleventh-hour Win32\ntesting above and beyond the call of duty), Michael G Schwern (for testing advice), and the rest\nof the CPAN testers (for testing generally).\n\nSpecial thanks to Tels for suggesting several speed and memory optimizations.\n\nAdditional thanks to: Edward Avis / Mattia Barbon / Tom Christiansen / Gerrit Haase / Gurusamy\nSarathy / Jarkko Hietaniemi (again) / Nikola Knezevic / John Kominetz / Nick Ing-Simmons /\nTassilo von Parseval / H. Dieter Pearcey / Slaven Rezic / Eric Roode / Peter Scott / Peter Somu\n/ Autrijus Tang (again) / Tels (again) / Juerd Waalboer / Todd Rinaldo\n",
            "subsections": []
        },
        "TODO": {
            "content": "More tests. (Stuff I didn't think of yet.)\n\nParagraph mode?\n\nFixed-length mode. Leave-blanks mode.\n\nMaybe an autolocking mode?\n\nFor many common uses of the module, the read cache is a liability. For example, a program that\ninserts a single record, or that scans the file once, will have a cache hit rate of zero. This\nsuggests a major optimization: The cache should be initially disabled. Here's a hybrid approach:\nInitially, the cache is disabled, but the cache code maintains statistics about how high the hit\nrate would be *if* it were enabled. When it sees the hit rate get high enough, it enables\nitself. The STAT comments in this code are the beginning of an implementation of this.\n\nRecord locking with fcntl()? Then the module might support an undo log and get real\ntransactions. What a tour de force that would be.\n\nKeeping track of the highest cached record. This would allow reads-in-a-row to skip the cache\nlookup faster (if reading from 1..N with empty cache at start, the last cached value will be\nalways N-1).\n\nMore tests.\n",
            "subsections": []
        }
    },
    "summary": "Tie::File - Access the lines of a disk file via a Perl array",
    "flags": [],
    "examples": [],
    "see_also": []
}