📄 perlfaq5.html
字号:
<P>To connect up to one filehandle to several output filehandles, it's easiestto use the <CODE>tee(1)</CODE> program if you have it, and let it take careof the multiplexing:<P><PRE> open (FH, "| tee file1 file2 file3");</PRE><P>Otherwise you'll have to write your own multiplexing print function -- oryour own tee program -- or use Tom Christiansen's, at <AHREF="../../tppmsgs/msgs1.htm#112" tppabs="http://www.perl.com/CPAN/authors/id/TOMC/scripts/tct.gz">http://www.perl.com/CPAN/authors/id/TOMC/scripts/tct.gz</A>,which is written in Perl.<P>In theory a IO::Tee class could be written, but to date we haven't seensuch.<P><P><HR><H3><A NAME="How_can_I_read_in_a_file_by_para">How can I read in a file by paragraphs?</A></H3>Use the <CODE>$\</CODE> variable (see <A HREF="../../tppmsgs/msgs1.htm#100" tppabs="http://www.perl.org/CPAN/doc/manual/html/pod/perlvar.html">the perlvar manpage</A> for details). You can either set it to <CODE>""</CODE> to eliminate empty paragraphs (<CODE>"abc\n\n\n\ndef"</CODE>, for instance, gets treated as two paragraphs and not three), or<CODE>"\n\n"</CODE> to accept empty paragraphs.<P><P><HR><H3><A NAME="How_can_I_read_a_single_characte">How can I read a single character from a file? From the keyboard?</A></H3>You can use the builtin <CODE>getc()</CODE> function for most filehandles, but it won't (easily) work on a terminal device. For <FONT SIZE=-1>STDIN,</FONT> either use the Term::ReadKey module from <FONT SIZE=-1>CPAN,</FONT> or use the sample code in<A HREF="../../tppmsgs/msgs0.htm#68" tppabs="http://www.perl.org/CPAN/doc/manual/html/pod/perlfunc.html#getc">getc</A>.<P>If your system supports <FONT SIZE=-1>POSIX,</FONT> you can use the following code, which you'llnote turns off echo processing as well.<P><PRE> #!/usr/bin/perl -w use strict; $| = 1; for (1..4) { my $got; print "gimme: "; $got = getone(); print "--> $got\n"; } exit;</PRE><P><PRE> BEGIN { use POSIX qw(:termios_h);</PRE><P><PRE> my ($term, $oterm, $echo, $noecho, $fd_stdin);</PRE><P><PRE> $fd_stdin = fileno(STDIN);</PRE><P><PRE> $term = POSIX::Termios->new(); $term->getattr($fd_stdin); $oterm = $term->getlflag();</PRE><P><PRE> $echo = ECHO | ECHOK | ICANON; $noecho = $oterm & ~$echo;</PRE><P><PRE> sub cbreak { $term->setlflag($noecho); $term->setcc(VTIME, 1); $term->setattr($fd_stdin, TCSANOW); }</PRE><P><PRE> sub cooked { $term->setlflag($oterm); $term->setcc(VTIME, 0); $term->setattr($fd_stdin, TCSANOW); }</PRE><P><PRE> sub getone { my $key = ''; cbreak(); sysread(STDIN, $key, 1); cooked(); return $key; }</PRE><P><PRE> }</PRE><P><PRE> END { cooked() }</PRE><P>The Term::ReadKey module from <FONT SIZE=-1>CPAN</FONT> may be easier to use:<P><PRE> use Term::ReadKey; open(TTY, "</dev/tty"); print "Gimme a char: "; ReadMode "raw"; $key = ReadKey 0, *TTY; ReadMode "normal"; printf "\nYou said %s, char number %03d\n", $key, ord $key;</PRE><P>For <FONT SIZE=-1>DOS</FONT> systems, Dan Carson <AHREF="MAILTO:dbc@tc.fluke.COM"><dbc@tc.fluke.COM></A> reports thefollowing:<P>To put the <FONT SIZE=-1>PC</FONT> in ``raw'' mode, use ioctl with some magic numbersgleaned from msdos.c (Perl source file) and Ralf Brown's interrupt list(comes across the net every so often):<P><PRE> $old_ioctl = ioctl(STDIN,0,0); # Gets device info $old_ioctl &= 0xff; ioctl(STDIN,1,$old_ioctl | 32); # Writes it back, setting bit 5</PRE><P>Then to read a single character:<P><PRE> sysread(STDIN,$c,1); # Read a single character</PRE><P>And to put the <FONT SIZE=-1>PC</FONT> back to ``cooked'' mode:<P><PRE> ioctl(STDIN,1,$old_ioctl); # Sets it back to cooked mode.</PRE><P>So now you have $c. If <CODE>ord($c) == 0</CODE>, you have a two byte code, which means you hit a special key. Read anotherbyte with <CODE>sysread(STDIN,$c,1)</CODE>, and that value tells you what combination it was according to this table:<P><PRE> # PC 2-byte keycodes = ^@ + the following:</PRE><P><PRE> # HEX KEYS # --- ---- # 0F SHF TAB # 10-19 ALT QWERTYUIOP # 1E-26 ALT ASDFGHJKL # 2C-32 ALT ZXCVBNM # 3B-44 F1-F10 # 47-49 HOME,UP,PgUp # 4B LEFT # 4D RIGHT # 4F-53 END,DOWN,PgDn,Ins,Del # 54-5D SHF F1-F10 # 5E-67 CTR F1-F10 # 68-71 ALT F1-F10 # 73-77 CTR LEFT,RIGHT,END,PgDn,HOME # 78-83 ALT 1234567890-= # 84 CTR PgUp</PRE><P>This is all trial and error <FONT SIZE=-1>I</FONT> did a long time ago, <FONT SIZE=-1>I</FONT> hope I'm reading the file that worked.<P><P><HR><H3><A NAME="How_can_I_tell_if_there_s_a_char">How can I tell if there's a character waiting on a filehandle?</A></H3>You should check out the Frequently Asked Questions list in comp.unix.* for things like this: the answer is essentially the same. It's very system dependent. Here's one solution that works on <FONT SIZE=-1>BSD</FONT> systems:<P><PRE> sub key_ready { my($rin, $nfd); vec($rin, fileno(STDIN), 1) = 1; return $nfd = select($rin,undef,undef,0); }</PRE><P>You should look into getting the Term::ReadKey extension from <FONT SIZE=-1>CPAN.</FONT><P><P><HR><H3><A NAME="How_do_I_open_a_file_without_blo">How do I open a file without blocking?</A></H3>You need to use the <FONT SIZE=-1>O_NDELAY</FONT> or <FONT SIZE=-1>O_NONBLOCK</FONT> flag from the Fcntl module in conjunction with <CODE>sysopen():</CODE><P><PRE> use Fcntl; sysopen(FH, "/tmp/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644) or die "can't open /tmp/somefile: $!":</PRE><P><P><HR><H3><A NAME="How_do_I_create_a_file_only_if_i">How do I create a file only if it doesn't exist?</A></H3>You need to use the <FONT SIZE=-1>O_CREAT</FONT> and <FONT SIZE=-1>O_EXCL</FONT> flags from the Fcntl module in conjunction with <CODE>sysopen():</CODE><P><PRE> use Fcntl; sysopen(FH, "/tmp/somefile", O_WRONLY|O_EXCL|O_CREAT, 0644) or die "can't open /tmp/somefile: $!":</PRE><P>Be warned that neither creation nor deletion of files is guaranteed to be an atomic operation over <FONT SIZE=-1>NFS.</FONT> That is, two processes might both successful create or unlink the same file!<P><P><HR><H3><A NAME="How_do_I_do_a_C_tail_f_in_perl">How do I do a <CODE>tail -f</CODE> in perl?</A></H3>First try<P><PRE> seek(GWFILE, 0, 1);</PRE><P>The statement <CODE>seek(GWFILE, 0, 1)</CODE> doesn't change the current position, but it does clear the end-of-file condition on the handle, so that the next <FONT SIZE=-1><GWFILE></FONT> makes Perl try again to read something.<P>If that doesn't work (it relies on features of your stdio implementation),then you need something more like this:<P><PRE> for (;;) { for ($curpos = tell(GWFILE); <GWFILE>; $curpos = tell(GWFILE)) { # search for some stuff and put it into files } # sleep for a while seek(GWFILE, $curpos, 0); # seek to where we had been }</PRE><P>If this still doesn't work, look into the <FONT SIZE=-1>POSIX</FONT> module. <FONT SIZE=-1>POSIX</FONT> defines the <CODE>clearerr()</CODE> method, which can remove the end of file condition on a filehandle. The method: read until end of file, <CODE>clearerr(),</CODE> read some more. Lather, rinse, repeat.<P><P><HR><H3><A NAME="How_do_I_dup_a_filehandle_in_P">How do I dup() a filehandle in Perl?</A></H3>If you check <A HREF="../../tppmsgs/msgs0.htm#68" tppabs="http://www.perl.org/CPAN/doc/manual/html/pod/perlfunc.html#open">open</A>, you'll see that several of the ways to call <CODE>open()</CODE> should dothe trick. For example:<P><PRE> open(LOG, ">>/tmp/logfile"); open(STDERR, ">&LOG");</PRE><P>Or even with a literal numeric descriptor:<P><PRE> $fd = $ENV{MHCONTEXTFD}; open(MHCONTEXT, "<&=$fd"); # like fdopen(3S)</PRE><P>Error checking has been left as an exercise for the reader.<P><P><HR><H3><A NAME="How_do_I_close_a_file_descriptor">How do I close a file descriptor by number?</A></H3>This should rarely be necessary, as the Perl <CODE>close()</CODE> function is to be used for things that Perl opened itself, even if it was a dup of a numeric descriptor, as with <FONT SIZE=-1>MHCONTEXT</FONT> above. But if you really have to, you may be able to do this:<P><PRE> require 'sys/syscall.ph'; $rc = syscall(&SYS_close, $fd + 0); # must force numeric die "can't sysclose $fd: $!" unless $rc == -1;</PRE><P><P><HR><H3><A NAME="Why_can_t_I_use_C_temp_foo_in">Why can't I use "C:\temp\foo" in DOS paths? What doesn't `C:\temp\foo.exe` work?</A></H3>Whoops! You just put a tab and a formfeed into that filename! Remember thatwithin double quoted strings (``like\this''), the backslash is an escapecharacter. The full list of these is in<A HREF="../../tppmsgs/msgs0.htm#69" tppabs="http://www.perl.org/CPAN/doc/manual/html/pod/perlop.html#Quote_and_Quote_like_Operators">Quote and Quote-like Operators</A>. Unsurprisingly, you don't have a file called ``c:(tab)emp(formfeed)oo'' or ``c:(tab)emp(formfeed)oo.exe'' on your <FONT SIZE=-1>DOS</FONT> filesystem.<P>Either single-quote your strings, or (preferably) use forward slashes. Since all <FONT SIZE=-1>DOS</FONT> and Windows versions since something like <FONT SIZE=-1>MS-DOS</FONT> 2.0 or so have treated <CODE>/</CODE> and <CODE>\</CODE> the same in a path, you might as well use the one that doesn't clash with Perl -- or the <FONT SIZE=-1>POSIX</FONT> shell, <FONT SIZE=-1>ANSI</FONT> <FONT SIZE=-1>C</FONT> and <FONT SIZE=-1>C++,</FONT> awk, Tcl, Java, or Python, just to mention a few.<P><P><HR><H3><A NAME="Why_doesn_t_glob_get_all_">Why doesn't glob("*.*") get all the files?</A></H3>Because even on non-Unix ports, Perl's glob function follows standard Unixglobbing semantics. You'll need <CODE>glob("*")</CODE> to get all (non-hidden) files.<P><P><HR><H3><A NAME="Why_does_Perl_let_me_delete_read">Why does Perl let me delete read-only files? Why does <CODE>-i</CODE> clobber protected files? Isn't this a bug in Perl?</A></H3>This is elaborately and painstakingly described in the ``Far More Than YouEvery Wanted To Know'' in <AHREF="../../tppmsgs/msgs1.htm#113" tppabs="http://www.perl.com/CPAN/doc/FMTEYEWTK/file-dir-perms">http://www.perl.com/CPAN/doc/FMTEYEWTK/file-dir-perms</A>.<P>The executive summary: learn how your filesystem works. The permissions ona file say what can happen to the data in that file. The permissions on adirectory say what can happen to the list of files in that directory. Ifyou delete a file, you're removing its name from the directory (so theoperation depends on the permissions of the directory, not of the file). Ifyou try to write to the file, the permissions of the file govern whetheryou're allowed to.<P><P><HR><H3><A NAME="How_do_I_select_a_random_line_fr">How do I select a random line from a file?</A></H3>Here's an algorithm from the Camel Book:<P><PRE> srand; rand($.) < 1 && ($line = $_) while <>;</PRE><P>This has a significant advantage in space over reading the whole file in.<P><P><HR><H2><A NAME="AUTHOR_AND_COPYRIGHT">AUTHOR AND COPYRIGHT</A></H2>Copyright (c) 1997 Tom Christiansen and Nathan Torkington. All rightsreserved. See <A HREF="perlfaq.html" tppabs="http://202.96.217.5/~xiaoyi/perlfaq.html">the perlfaq manpage</A> for distribution information.<P></DL> </BODY> </HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -