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

📄 perlopentut.1

📁 视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.
💻 1
📖 第 1 页 / 共 4 页
字号:
command writes to its standard output show up on your handle for reading.For example:.PP.Vb 3\&    open(NET, "netstat \-i \-n |")    || die "can\*(Aqt fork netstat: $!";\&    while (<NET>) { }               # do something with input\&    close(NET)                      || die "can\*(Aqt close netstat: $!";.Ve.PPWhat happens if you try to open a pipe to or from a non-existentcommand?  If possible, Perl will detect the failure and set \f(CW$!\fR asusual.  But if the command contains special shell characters, such as\&\f(CW\*(C`>\*(C'\fR or \f(CW\*(C`*\*(C'\fR, called 'metacharacters', Perl does not execute thecommand directly.  Instead, Perl runs the shell, which then tries torun the command.  This means that it's the shell that gets the errorindication.  In such a case, the \f(CW\*(C`open\*(C'\fR call will only indicatefailure if Perl can't even run the shell.  See \*(L"How can Icapture \s-1STDERR\s0 from an external command?\*(R" in perlfaq8 to see how to cope withthis.  There's also an explanation in perlipc..PPIf you would like to open a bidirectional pipe, the IPC::Open2library will handle this for you.  Check out \&\*(L"Bidirectional Communication with Another Process\*(R" in perlipc.Sh "The Minus File".IX Subsection "The Minus File"Again following the lead of the standard shell utilities, Perl's\&\f(CW\*(C`open\*(C'\fR function treats a file whose name is a single minus, \*(L"\-\*(R", in aspecial way.  If you open minus for reading, it really means to accessthe standard input.  If you open minus for writing, it really means toaccess the standard output..PPIf minus can be used as the default input or default output, what happensif you open a pipe into or out of minus?  What's the default command itwould run?  The same script as you're currently running!  This is actuallya stealth \f(CW\*(C`fork\*(C'\fR hidden inside an \f(CW\*(C`open\*(C'\fR call.  See \&\*(L"Safe Pipe Opens\*(R" in perlipc for details..Sh "Mixing Reads and Writes".IX Subsection "Mixing Reads and Writes"It is possible to specify both read and write access.  All you do isadd a \*(L"+\*(R" symbol in front of the redirection.  But as in the shell,using a less-than on a file never creates a new file; it only opens anexisting one.  On the other hand, using a greater-than always clobbers(truncates to zero length) an existing file, or creates a brand-new oneif there isn't an old one.  Adding a \*(L"+\*(R" for read-write doesn't affectwhether it only works on existing files or always clobbers existing ones..PP.Vb 2\&    open(WTMP, "+< /usr/adm/wtmp") \&        || die "can\*(Aqt open /usr/adm/wtmp: $!";\&\&    open(SCREEN, "+> lkscreen")\&        || die "can\*(Aqt open lkscreen: $!";\&\&    open(LOGFILE, "+>> /var/log/applog")\&        || die "can\*(Aqt open /var/log/applog: $!";.Ve.PPThe first one won't create a new file, and the second one will alwaysclobber an old one.  The third one will create a new file if necessaryand not clobber an old one, and it will allow you to read at any pointin the file, but all writes will always go to the end.  In short,the first case is substantially more common than the second and thirdcases, which are almost always wrong.  (If you know C, the plus inPerl's \f(CW\*(C`open\*(C'\fR is historically derived from the one in C's fopen(3S),which it ultimately calls.).PPIn fact, when it comes to updating a file, unless you're working ona binary file as in the \s-1WTMP\s0 case above, you probably don't want touse this approach for updating.  Instead, Perl's \fB\-i\fR flag comes tothe rescue.  The following command takes all the C, \*(C+, or yacc sourceor header files and changes all their foo's to bar's, leavingthe old version in the original filename with a \*(L".orig\*(R" tackedon the end:.PP.Vb 1\&    $ perl \-i.orig \-pe \*(Aqs/\ebfoo\eb/bar/g\*(Aq *.[Cchy].Ve.PPThis is a short cut for some renaming games that are reallythe best way to update textfiles.  See the second question in perlfaq5 for more details..Sh "Filters".IX Subsection "Filters"One of the most common uses for \f(CW\*(C`open\*(C'\fR is one you nevereven notice.  When you process the \s-1ARGV\s0 filehandle using\&\f(CW\*(C`<ARGV>\*(C'\fR, Perl actually does an implicit open on each file in \f(CW@ARGV\fR.  Thus a program called like this:.PP.Vb 1\&    $ myprogram file1 file2 file3.Ve.PPcan have all its files opened and processed one at a timeusing a construct no more complex than:.PP.Vb 3\&    while (<>) {\&        # do something with $_\&    }.Ve.PPIf \f(CW@ARGV\fR is empty when the loop first begins, Perl pretends you've openedup minus, that is, the standard input.  In fact, \f(CW$ARGV\fR, the currentlyopen file during \f(CW\*(C`<ARGV>\*(C'\fR processing, is even set to \*(L"\-\*(R"in these circumstances..PPYou are welcome to pre-process your \f(CW@ARGV\fR before starting the loop tomake sure it's to your liking.  One reason to do this might be to removecommand options beginning with a minus.  While you can always roll thesimple ones by hand, the Getopts modules are good for this:.PP.Vb 1\&    use Getopt::Std;\&\&    # \-v, \-D, \-o ARG, sets $opt_v, $opt_D, $opt_o\&    getopts("vDo:");            \&\&    # \-v, \-D, \-o ARG, sets $args{v}, $args{D}, $args{o}\&    getopts("vDo:", \e%args);.Ve.PPOr the standard Getopt::Long module to permit named arguments:.PP.Vb 5\&    use Getopt::Long;\&    GetOptions( "verbose"  => \e$verbose,        # \-\-verbose\&                "Debug"    => \e$debug,          # \-\-Debug\&                "output=s" => \e$output );       \&            # \-\-output=somestring or \-\-output somestring.Ve.PPAnother reason for preprocessing arguments is to make an emptyargument list default to all files:.PP.Vb 1\&    @ARGV = glob("*") unless @ARGV;.Ve.PPYou could even filter out all but plain, text files.  This is a bitsilent, of course, and you might prefer to mention them on the way..PP.Vb 1\&    @ARGV = grep { \-f && \-T } @ARGV;.Ve.PPIf you're using the \fB\-n\fR or \fB\-p\fR command-line options, youshould put changes to \f(CW@ARGV\fR in a \f(CW\*(C`BEGIN{}\*(C'\fR block..PPRemember that a normal \f(CW\*(C`open\*(C'\fR has special properties, in that it mightcall fopen(3S) or it might called popen(3S), depending on what itsargument looks like; that's why it's sometimes called \*(L"magic open\*(R".Here's an example:.PP.Vb 3\&    $pwdinfo = \`domainname\` =~ /^(\e(none\e))?$/\&                    ? \*(Aq< /etc/passwd\*(Aq\&                    : \*(Aqypcat passwd |\*(Aq;\&\&    open(PWD, $pwdinfo)                 \&                or die "can\*(Aqt open $pwdinfo: $!";.Ve.PPThis sort of thing also comes into play in filter processing.  Because\&\f(CW\*(C`<ARGV>\*(C'\fR processing employs the normal, shell-style Perl \f(CW\*(C`open\*(C'\fR,it respects all the special things we've already seen:.PP.Vb 1\&    $ myprogram f1 "cmd1|" \- f2 "cmd2|" f3 < tmpfile.Ve.PPThat program will read from the file \fIf1\fR, the process \fIcmd1\fR, standardinput (\fItmpfile\fR in this case), the \fIf2\fR file, the \fIcmd2\fR command,and finally the \fIf3\fR file..PPYes, this also means that if you have files named \*(L"\-\*(R" (and so on) inyour directory, they won't be processed as literal files by \f(CW\*(C`open\*(C'\fR.You'll need to pass them as \*(L"./\-\*(R", much as you would for the \fIrm\fR program,or you could use \f(CW\*(C`sysopen\*(C'\fR as described below..PPOne of the more interesting applications is to change files of a certainname into pipes.  For example, to autoprocess gzipped or compressedfiles by decompressing them with \fIgzip\fR:.PP.Vb 1\&    @ARGV = map { /^\e.(gz|Z)$/ ? "gzip \-dc $_ |" : $_  } @ARGV;.Ve.PPOr, if you have the \fI\s-1GET\s0\fR program installed from \s-1LWP\s0,you can fetch URLs before processing them:.PP.Vb 1\&    @ARGV = map { m#^\ew+://# ? "GET $_ |" : $_ } @ARGV;.Ve.PPIt's not for nothing that this is called magic \f(CW\*(C`<ARGV>\*(C'\fR.Pretty nifty, eh?.SH "Open a\*` la C".IX Header "Open a` la C"If you want the convenience of the shell, then Perl's \f(CW\*(C`open\*(C'\fR isdefinitely the way to go.  On the other hand, if you want finer precisionthan C's simplistic fopen(3S) provides you should look to Perl's\&\f(CW\*(C`sysopen\*(C'\fR, which is a direct hook into the \fIopen\fR\|(2) system call.That does mean it's a bit more involved, but that's the price of precision..PP\&\f(CW\*(C`sysopen\*(C'\fR takes 3 (or 4) arguments..PP.Vb 1\&    sysopen HANDLE, PATH, FLAGS, [MASK].Ve.PPThe \s-1HANDLE\s0 argument is a filehandle just as with \f(CW\*(C`open\*(C'\fR.  The \s-1PATH\s0 isa literal path, one that doesn't pay attention to any greater-thans orless-thans or pipes or minuses, nor ignore whitespace.  If it's there,it's part of the path.  The \s-1FLAGS\s0 argument contains one or more valuesderived from the Fcntl module that have been or'd together using thebitwise \*(L"|\*(R" operator.  The final argument, the \s-1MASK\s0, is optional; ifpresent, it is combined with the user's current umask for the creationmode of the file.  You should usually omit this..PPAlthough the traditional values of read-only, write-only, and read-writeare 0, 1, and 2 respectively, this is known not to hold true on somesystems.  Instead, it's best to load in the appropriate constants firstfrom the Fcntl module, which supplies the following standard flags:.PP.Vb 8\&    O_RDONLY            Read only\&    O_WRONLY            Write only\&    O_RDWR              Read and write\&    O_CREAT             Create the file if it doesn\*(Aqt exist\&    O_EXCL              Fail if the file already exists\&    O_APPEND            Append to the file\&    O_TRUNC             Truncate the file\&    O_NONBLOCK          Non\-blocking access.Ve.PPLess common flags that are sometimes available on some operatingsystems include \f(CW\*(C`O_BINARY\*(C'\fR, \f(CW\*(C`O_TEXT\*(C'\fR, \f(CW\*(C`O_SHLOCK\*(C'\fR, \f(CW\*(C`O_EXLOCK\*(C'\fR,\&\f(CW\*(C`O_DEFER\*(C'\fR, \f(CW\*(C`O_SYNC\*(C'\fR, \f(CW\*(C`O_ASYNC\*(C'\fR, \f(CW\*(C`O_DSYNC\*(C'\fR, \f(CW\*(C`O_RSYNC\*(C'\fR,\&\f(CW\*(C`O_NOCTTY\*(C'\fR, \f(CW\*(C`O_NDELAY\*(C'\fR and \f(CW\*(C`O_LARGEFILE\*(C'\fR.  Consult your \fIopen\fR\|(2)manpage or its local equivalent for details.  (Note: starting fromPerl release 5.6 the \f(CW\*(C`O_LARGEFILE\*(C'\fR flag, if available, is automaticallyadded to the \fIsysopen()\fR flags because large files are the default.).PPHere's how to use \f(CW\*(C`sysopen\*(C'\fR to emulate the simple \f(CW\*(C`open\*(C'\fR calls we hadbefore.  We'll omit the \f(CW\*(C`|| die $!\*(C'\fR checks for clarity, but make sureyou always check the return values in real code.  These aren't quitethe same, since \f(CW\*(C`open\*(C'\fR will trim leading and trailing whitespace,but you'll get the idea..PPTo open a file for reading:.PP.Vb 2\&    open(FH, "< $path");\&    sysopen(FH, $path, O_RDONLY);.Ve.PPTo open a file for writing, creating a new file if needed or else truncatingan old file:.PP.Vb 2\&    open(FH, "> $path");\&    sysopen(FH, $path, O_WRONLY | O_TRUNC | O_CREAT);.Ve.PPTo open a file for appending, creating one if necessary:.PP.Vb 2\&    open(FH, ">> $path");\&    sysopen(FH, $path, O_WRONLY | O_APPEND | O_CREAT);.Ve.PPTo open a file for update, where the file must already exist:.PP.Vb 2\&    open(FH, "+< $path");\&    sysopen(FH, $path, O_RDWR);.Ve.PPAnd here are things you can do with \f(CW\*(C`sysopen\*(C'\fR that you cannot do witha regular \f(CW\*(C`open\*(C'\fR.  As you'll see, it's just a matter of controlling theflags in the third argument..PPTo open a file for writing, creating a new file which must not previouslyexist:.PP.Vb 1\&    sysopen(FH, $path, O_WRONLY | O_EXCL | O_CREAT);.Ve.PPTo open a file for appending, where that file must already exist:.PP.Vb 1\&    sysopen(FH, $path, O_WRONLY | O_APPEND);.Ve.PPTo open a file for update, creating a new file if necessary:.PP.Vb 1\&    sysopen(FH, $path, O_RDWR | O_CREAT);

⌨️ 快捷键说明

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