⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tie::file.3

📁 视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.
💻 3
📖 第 1 页 / 共 2 页
字号:
\&\f(CW\*(C`Tie::File\*(C'\fR maintains an internal table of the byte offset of eachrecord it has seen in the file..PPWhen you use \f(CW\*(C`flock\*(C'\fR to lock the file, \f(CW\*(C`Tie::File\*(C'\fR assumes that theread cache is no longer trustworthy, because another process mighthave modified the file since the last time it was read.  Therefore, asuccessful call to \f(CW\*(C`flock\*(C'\fR discards the contents of the read cacheand the internal record offset table..PP\&\f(CW\*(C`Tie::File\*(C'\fR promises that the following sequence of operations willbe safe:.PP.Vb 2\&        my $o = tie @array, "Tie::File", $filename;\&        $o\->flock;.Ve.PPIn particular, \f(CW\*(C`Tie::File\*(C'\fR will \fInot\fR read or write the file duringthe \f(CW\*(C`tie\*(C'\fR call.  (Exception: Using \f(CW\*(C`mode => O_TRUNC\*(C'\fR will, ofcourse, erase the file during the \f(CW\*(C`tie\*(C'\fR call.  If you want to do thissafely, then open the file without \f(CW\*(C`O_TRUNC\*(C'\fR, lock the file, and use\&\f(CW\*(C`@array = ()\*(C'\fR.).PPThe best way to unlock a file is to discard the object and untie thearray.  It is probably unsafe to unlock the file without also untyingit, because if you do, changes may remain unwritten inside the object.That is why there is no shortcut for unlocking.  If you really want tounlock the file prematurely, you know what to do; if you don't knowwhat to do, then don't do it..PPAll the usual warnings about file locking apply here.  In particular,note that file locking in Perl is \fBadvisory\fR, which means thatholding a lock will not prevent anyone else from reading, writing, orerasing the file; it only prevents them from getting another lock atthe same time.  Locks are analogous to green traffic lights: If youhave a green light, that does not prevent the idiot coming the otherway from plowing into you sideways; it merely guarantees to you thatthe idiot does not also have a green light at the same time..ie n .Sh """autochomp""".el .Sh "\f(CWautochomp\fP".IX Subsection "autochomp".Vb 2\&        my $old_value = $o\->autochomp(0);    # disable autochomp option\&        my $old_value = $o\->autochomp(1);    #  enable autochomp option\&\&        my $ac = $o\->autochomp();   # recover current value.Ve.PPSee \*(L"autochomp\*(R", above..ie n .Sh """defer""\fP, \f(CW""flush""\fP, \f(CW""discard""\fP, and \f(CW""autodefer""".el .Sh "\f(CWdefer\fP, \f(CWflush\fP, \f(CWdiscard\fP, and \f(CWautodefer\fP".IX Subsection "defer, flush, discard, and autodefer"See \*(L"Deferred Writing\*(R", below..ie n .Sh """offset""".el .Sh "\f(CWoffset\fP".IX Subsection "offset".Vb 1\&        $off = $o\->offset($n);.Ve.PPThis method returns the byte offset of the start of the \f(CW$n\fRth recordin the file.  If there is no such record, it returns an undefinedvalue..SH "Tying to an already-opened filehandle".IX Header "Tying to an already-opened filehandle"If \f(CW$fh\fR is a filehandle, such as is returned by \f(CW\*(C`IO::File\*(C'\fR or oneof the other \f(CW\*(C`IO\*(C'\fR modules, you may use:.PP.Vb 1\&        tie @array, \*(AqTie::File\*(Aq, $fh, ...;.Ve.PPSimilarly if you opened that handle \f(CW\*(C`FH\*(C'\fR with regular \f(CW\*(C`open\*(C'\fR or\&\f(CW\*(C`sysopen\*(C'\fR, you may use:.PP.Vb 1\&        tie @array, \*(AqTie::File\*(Aq, \e*FH, ...;.Ve.PPHandles that were opened write-only won't work.  Handles that wereopened read-only will work as long as you don't try to modify thearray.  Handles must be attached to seekable sources of data\-\-\-thatmeans no pipes or sockets.  If \f(CW\*(C`Tie::File\*(C'\fR can detect that yousupplied a non-seekable handle, the \f(CW\*(C`tie\*(C'\fR call will throw anexception.  (On Unix systems, it can detect this.).PPNote that Tie::File will only close any filehandles that it openedinternally.  If you passed it a filehandle as above, you \*(L"own\*(R" thefilehandle, and are responsible for closing it after you have untiedthe \f(CW@array\fR..SH "Deferred Writing".IX Header "Deferred Writing"(This is an advanced feature.  Skip this section on first reading.).PPNormally, modifying a \f(CW\*(C`Tie::File\*(C'\fR array writes to the underlying fileimmediately.  Every assignment like \f(CW\*(C`$a[3] = ...\*(C'\fR rewrites as much ofthe file as is necessary; typically, everything from line 3 throughthe end will need to be rewritten.  This is the simplest and mosttransparent behavior.  Performance even for large files is reasonablygood..PPHowever, under some circumstances, this behavior may be excessivelyslow.  For example, suppose you have a million-record file, and youwant to do:.PP.Vb 3\&        for (@FILE) {\&          $_ = "> $_";\&        }.Ve.PPThe first time through the loop, you will rewrite the entire file,from line 0 through the end.  The second time through the loop, youwill rewrite the entire file from line 1 through the end.  The thirdtime through the loop, you will rewrite the entire file from line 2 tothe end.  And so on..PPIf the performance in such cases is unacceptable, you may defer theactual writing, and then have it done all at once.  The following loopwill perform much better for large files:.PP.Vb 5\&        (tied @a)\->defer;\&        for (@a) {\&          $_ = "> $_";\&        }\&        (tied @a)\->flush;.Ve.PPIf \f(CW\*(C`Tie::File\*(C'\fR's memory limit is large enough, all the writing willdone in memory.  Then, when you call \f(CW\*(C`\->flush\*(C'\fR, the entire filewill be rewritten in a single pass..PP(Actually, the preceding discussion is something of a fib.  You don'tneed to enable deferred writing to get good performance for thiscommon case, because \f(CW\*(C`Tie::File\*(C'\fR will do it for you automaticallyunless you specifically tell it not to.  See \*(L"autodeferring\*(R",below.).PPCalling \f(CW\*(C`\->flush\*(C'\fR returns the array to immediate-write mode.  Ifyou wish to discard the deferred writes, you may call \f(CW\*(C`\->discard\*(C'\fRinstead of \f(CW\*(C`\->flush\*(C'\fR.  Note that in some cases, some of the datawill have been written already, and it will be too late for\&\f(CW\*(C`\->discard\*(C'\fR to discard all the changes.  Support for\&\f(CW\*(C`\->discard\*(C'\fR may be withdrawn in a future version of \f(CW\*(C`Tie::File\*(C'\fR..PPDeferred writes are cached in memory up to the limit specified by the\&\f(CW\*(C`dw_size\*(C'\fR option (see above).  If the deferred-write buffer is fulland you try to write still more deferred data, the buffer will beflushed.  All buffered data will be written immediately, the bufferwill be emptied, and the now-empty space will be used for futuredeferred writes..PPIf the deferred-write buffer isn't yet full, but the total size of thebuffer and the read cache would exceed the \f(CW\*(C`memory\*(C'\fR limit, the oldestrecords will be expired from the read cache until the total size isunder the limit..PP\&\f(CW\*(C`push\*(C'\fR, \f(CW\*(C`pop\*(C'\fR, \f(CW\*(C`shift\*(C'\fR, \f(CW\*(C`unshift\*(C'\fR, and \f(CW\*(C`splice\*(C'\fR cannot bedeferred.  When you perform one of these operations, any deferred datais written to the file and the operation is performed immediately.This may change in a future version..PPIf you resize the array with deferred writing enabled, the file willbe resized immediately, but deferred records will not be written.This has a surprising consequence: \f(CW\*(C`@a = (...)\*(C'\fR erases the fileimmediately, but the writing of the actual data is deferred.  Thismight be a bug.  If it is a bug, it will be fixed in a future version..Sh "Autodeferring".IX Subsection "Autodeferring"\&\f(CW\*(C`Tie::File\*(C'\fR tries to guess when deferred writing might be helpful,and to turn it on and off automatically..PP.Vb 3\&        for (@a) {\&          $_ = "> $_";\&        }.Ve.PPIn this example, only the first two assignments will be doneimmediately; after this, all the changes to the file will be deferredup to the user-specified memory limit..PPYou should usually be able to ignore this and just use the modulewithout thinking about deferring.  However, special applications mayrequire fine control over which writes are deferred, or may requirethat all writes be immediate.  To disable the autodeferment feature,use.PP.Vb 1\&        (tied @o)\->autodefer(0);.Ve.PPor.PP.Vb 1\&        tie @array, \*(AqTie::File\*(Aq, $file, autodefer => 0;.Ve.PPSimilarly, \f(CW\*(C`\->autodefer(1)\*(C'\fR re-enables autodeferment, and \&\f(CW\*(C`\->autodefer()\*(C'\fR recovers the current value of the autodefer setting..SH "CONCURRENT ACCESS TO FILES".IX Header "CONCURRENT ACCESS TO FILES"Caching and deferred writing are inappropriate if you want the samefile to be accessed simultaneously from more than one process.  Otheroptimizations performed internally by this module are alsoincompatible with concurrent access.  A future version of this module willsupport a \f(CW\*(C`concurrent => 1\*(C'\fR option that enables safe concurrent access..PPPrevious versions of this documentation suggested using \f(CW\*(C`memory=> 0\*(C'\fR for safe concurrent access.  This was mistaken.  Tie::Filewill not support safe concurrent access before version 0.98..SH "CAVEATS".IX Header "CAVEATS"(That's Latin for 'warnings'.).IP "\(bu" 4Reasonable effort was made to make this module efficient.  Nevertheless,changing the size of a record in the middle of a large file willalways be fairly slow, because everything after the new record must bemoved..IP "\(bu" 4The behavior of tied arrays is not precisely the same as for regulararrays.  For example:.Sp.Vb 2\&        # This DOES print "How unusual!"\&        undef $a[10];  print "How unusual!\en" if defined $a[10];.Ve.Sp\&\f(CW\*(C`undef\*(C'\fR\-ing a \f(CW\*(C`Tie::File\*(C'\fR array element just blanks out thecorresponding record in the file.  When you read it back again, you'llget the empty string, so the supposedly\-\f(CW\*(C`undef\*(C'\fR'ed value will bedefined.  Similarly, if you have \f(CW\*(C`autochomp\*(C'\fR disabled, then.Sp.Vb 3\&        # This DOES print "How unusual!" if \*(Aqautochomp\*(Aq is disabled\&        undef $a[10];\&        print "How unusual!\en" if $a[10];.Ve.SpBecause when \f(CW\*(C`autochomp\*(C'\fR is disabled, \f(CW$a[10]\fR will read back as\&\f(CW"\en"\fR (or whatever the record separator string is.).SpThere are other minor differences, particularly regarding \f(CW\*(C`exists\*(C'\fRand \f(CW\*(C`delete\*(C'\fR, but in general, the correspondence is extremely close..IP "\(bu" 4I have supposed that since this module is concerned with file I/O,almost all normal use of it will be heavily I/O bound.  This meansthat the time to maintain complicated data structures inside themodule will be dominated by the time to actually perform the I/O.When there was an opportunity to spend \s-1CPU\s0 time to avoid doing I/O, Iusually tried to take it..IP "\(bu" 4You might be tempted to think that deferred writing is liketransactions, with \f(CW\*(C`flush\*(C'\fR as \f(CW\*(C`commit\*(C'\fR and \f(CW\*(C`discard\*(C'\fR as\&\f(CW\*(C`rollback\*(C'\fR, but it isn't, so don't..IP "\(bu" 4There is a large memory overhead for each record offset and for eachcache entry: about 310 bytes per cached data record, and about 21 bytes per offset table entry..SpThe per-record overhead will limit the maximum number of records youcan access per file. Note that \fIaccessing\fR the length of the arrayvia \f(CW\*(C`$x = scalar @tied_file\*(C'\fR accesses \fBall\fR records and stores theiroffsets.  The same for \f(CW\*(C`foreach (@tied_file)\*(C'\fR, even if you exit theloop early..SH "SUBCLASSING".IX Header "SUBCLASSING"This version promises absolutely nothing about the internals, whichmay change without notice.  A future version of the module will have awell-defined and stable subclassing \s-1API\s0..ie n .SH "WHAT ABOUT ""DB_File""?".el .SH "WHAT ABOUT \f(CWDB_File\fP?".IX Header "WHAT ABOUT DB_File?"People sometimes point out that DB_File will do something similar,and ask why \f(CW\*(C`Tie::File\*(C'\fR module is necessary..PPThere are a number of reasons that you might prefer \f(CW\*(C`Tie::File\*(C'\fR.A list is available at \f(CW\*(C`http://perl.plover.com/TieFile/why\-not\-DB_File\*(C'\fR..SH "AUTHOR".IX Header "AUTHOR"Mark Jason Dominus.PPTo contact the author, send email to: \f(CW\*(C`mjd\-perl\-tiefile+@plover.com\*(C'\fR.PPTo receive an announcement whenever a new version of this module isreleased, send a blank email message to\&\f(CW\*(C`mjd\-perl\-tiefile\-subscribe@plover.com\*(C'\fR..PPThe most recent version of this module, including documentation andany news of importance, will be available at.PP.Vb 1\&        http://perl.plover.com/TieFile/.Ve.SH "LICENSE".IX Header "LICENSE"\&\f(CW\*(C`Tie::File\*(C'\fR version 0.97 is copyright (C) 2003 Mark Jason Dominus..PPThis library is free software; you may redistribute it and/or modifyit under the same terms as Perl itself..PPThese terms are your choice of any of (1) the Perl Artistic Licence,or (2) version 2 of the \s-1GNU\s0 General Public License as published by theFree Software Foundation, or (3) any later version of the \s-1GNU\s0 GeneralPublic License..PPThis library is distributed in the hope that it will be useful,but \s-1WITHOUT\s0 \s-1ANY\s0 \s-1WARRANTY\s0; without even the implied warranty of\&\s-1MERCHANTABILITY\s0 or \s-1FITNESS\s0 \s-1FOR\s0 A \s-1PARTICULAR\s0 \s-1PURPOSE\s0.  See the\&\s-1GNU\s0 General Public License for more details..PPYou should have received a copy of the \s-1GNU\s0 General Public Licensealong with this library program; it should be in the file \f(CW\*(C`COPYING\*(C'\fR.If not, write to the Free Software Foundation, Inc., 51 Franklin Street,Fifth Floor, Boston, \s-1MA\s0  02110\-1301, \s-1USA\s0.PPFor licensing inquiries, contact the author at:.PP.Vb 3\&        Mark Jason Dominus\&        255 S. Warnock St.\&        Philadelphia, PA 19107.Ve.SH "WARRANTY".IX Header "WARRANTY"\&\f(CW\*(C`Tie::File\*(C'\fR version 0.97 comes with \s-1ABSOLUTELY\s0 \s-1NO\s0 \s-1WARRANTY\s0.For details, see the license..SH "THANKS".IX Header "THANKS"Gigantic thanks to Jarkko Hietaniemi, for agreeing to put this in thecore when I hadn't written it yet, and for generally being helpful,supportive, and competent.  (Usually the rule is \*(L"choose any one.\*(R")Also big thanks to Abhijit Menon-Sen for all of the same things..PPSpecial thanks to Craig Berry and Peter Prymmer (for \s-1VMS\s0 portabilityhelp), Randy Kobes (for Win32 portability help), Clinton Pierce andAutrijus Tang (for heroic eleventh-hour Win32 testing above and beyondthe call of duty), Michael G Schwern (for testing advice), and therest of the \s-1CPAN\s0 testers (for testing generally)..PPSpecial thanks to Tels for suggesting several speed and memoryoptimizations..PPAdditional thanks to:Edward Avis /Mattia Barbon /Tom Christiansen /Gerrit Haase /Gurusamy Sarathy /Jarkko Hietaniemi (again) /Nikola Knezevic /John Kominetz /Nick Ing-Simmons /Tassilo von Parseval /H. Dieter Pearcey /Slaven Rezic /Eric Roode /Peter Scott /Peter Somu /Autrijus Tang (again) /Tels (again) /Juerd Waalboer.SH "TODO".IX Header "TODO"More tests.  (Stuff I didn't think of yet.).PPParagraph mode?.PPFixed-length mode.  Leave-blanks mode..PPMaybe an autolocking mode?.PPFor many common uses of the module, the read cache is a liability.For example, a program that inserts a single record, or that scans thefile once, will have a cache hit rate of zero.  This suggests a majoroptimization: The cache should be initially disabled.  Here's a hybridapproach: Initially, the cache is disabled, but the cache codemaintains statistics about how high the hit rate would be *if* it wereenabled.  When it sees the hit rate get high enough, it enablesitself.  The \s-1STAT\s0 comments in this code are the beginning of animplementation of this..PPRecord locking with \fIfcntl()\fR?  Then the module might support an undolog and get real transactions.  What a tour de force that would be..PPKeeping track of the highest cached record. This would allow reads-in-a-rowto skip the cache lookup faster (if reading from 1..N with empty cache atstart, the last cached value will be always N\-1)..PPMore tests.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -