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

📄 perlfaq5.pod

📁 视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.
💻 POD
📖 第 1 页 / 共 3 页
字号:
days as a floating point number. Some platforms may not haveall of these times.  See L<perlport> for details. Toretrieve the "raw" time in seconds since the epoch, youwould call the stat function, then use localtime(),gmtime(), or POSIX::strftime() to convert this intohuman-readable form.Here's an example:	$write_secs = (stat($file))[9];	printf "file %s updated at %s\n", $file,	scalar localtime($write_secs);If you prefer something more legible, use the File::stat module(part of the standard distribution in version 5.004 and later):	# error checking left as an exercise for reader.	use File::stat;	use Time::localtime;	$date_string = ctime(stat($file)->mtime);	print "file $file updated at $date_string\n";The POSIX::strftime() approach has the benefit of being,in theory, independent of the current locale.  See L<perllocale>for details.=head2 How do I set a file's timestamp in perl?X<timestamp> X<file, timestamp>You use the utime() function documented in L<perlfunc/utime>.By way of example, here's a little program that copies theread and write times from its first argument to all the restof them.	if (@ARGV < 2) {		die "usage: cptimes timestamp_file other_files ...\n";		}	$timestamp = shift;	($atime, $mtime) = (stat($timestamp))[8,9];	utime $atime, $mtime, @ARGV;Error checking is, as usual, left as an exercise for the reader.The perldoc for utime also has an example that has the sameeffect as touch(1) on files that I<already exist>.Certain file systems have a limited ability to store the timeson a file at the expected level of precision.  For example, theFAT and HPFS filesystem are unable to create dates on files witha finer granularity than two seconds.  This is a limitation ofthe filesystems, not of utime().=head2 How do I print to more than one file at once?X<print, to multiple files>To connect one filehandle to several output filehandles,you can use the IO::Tee or Tie::FileHandle::Multiplex modules.If you only have to do this once, you can print individuallyto each filehandle.	for $fh (FH1, FH2, FH3) { print $fh "whatever\n" }=head2 How can I read in an entire file all at once?X<slurp> X<file, slurping>You can use the File::Slurp module to do it in one step.	use File::Slurp;	$all_of_it = read_file($filename); # entire file in scalar	@all_lines = read_file($filename); # one line perl elementThe customary Perl approach for processing all the lines in a file is todo so one line at a time:	open (INPUT, $file) 	|| die "can't open $file: $!";	while (<INPUT>) {		chomp;		# do something with $_		}	close(INPUT)	    	|| die "can't close $file: $!";This is tremendously more efficient than reading the entire file intomemory as an array of lines and then processing it one element at a time,which is often--if not almost always--the wrong approach.  Wheneveryou see someone do this:	@lines = <INPUT>;you should think long and hard about why you need everything loaded atonce.  It's just not a scalable solution.  You might also find it morefun to use the standard Tie::File module, or the DB_File module's$DB_RECNO bindings, which allow you to tie an array to a file so thataccessing an element the array actually accesses the correspondingline in the file.You can read the entire filehandle contents into a scalar.	{	local(*INPUT, $/);	open (INPUT, $file) 	|| die "can't open $file: $!";	$var = <INPUT>;	}That temporarily undefs your record separator, and will automaticallyclose the file at block exit.  If the file is already open, just use this:	$var = do { local $/; <INPUT> };For ordinary files you can also use the read function.	read( INPUT, $var, -s INPUT );The third argument tests the byte size of the data on the INPUT filehandleand reads that many bytes into the buffer $var.=head2 How can I read in a file by paragraphs?X<file, reading by paragraphs>Use the C<$/> variable (see L<perlvar> for details).  You can eitherset it to C<""> to eliminate empty paragraphs (C<"abc\n\n\n\ndef">,for instance, gets treated as two paragraphs and not three), orC<"\n\n"> to accept empty paragraphs.Note that a blank line must have no blanks in it.  ThusS<C<"fred\n \nstuff\n\n">> is one paragraph, but C<"fred\n\nstuff\n\n"> is two.=head2 How can I read a single character from a file?  From the keyboard?X<getc> X<file, reading one character at a time>You can use the builtin C<getc()> function for most filehandles, butit won't (easily) work on a terminal device.  For STDIN, either usethe Term::ReadKey module from CPAN or use the sample code inL<perlfunc/getc>.If your system supports the portable operating system programminginterface (POSIX), you can use the following code, which you'll noteturns off echo processing as well.	#!/usr/bin/perl -w	use strict;	$| = 1;	for (1..4) {		my $got;		print "gimme: ";		$got = getone();		print "--> $got\n";		}    exit;	BEGIN {	use POSIX qw(:termios_h);	my ($term, $oterm, $echo, $noecho, $fd_stdin);	$fd_stdin = fileno(STDIN);	$term     = POSIX::Termios->new();	$term->getattr($fd_stdin);	$oterm     = $term->getlflag();	$echo     = ECHO | ECHOK | ICANON;	$noecho   = $oterm & ~$echo;	sub cbreak {		$term->setlflag($noecho);		$term->setcc(VTIME, 1);		$term->setattr($fd_stdin, TCSANOW);		}	sub cooked {		$term->setlflag($oterm);		$term->setcc(VTIME, 0);		$term->setattr($fd_stdin, TCSANOW);		}	sub getone {		my $key = '';		cbreak();		sysread(STDIN, $key, 1);		cooked();		return $key;		}	}	END { cooked() }The Term::ReadKey module from CPAN may be easier to use.  Recent versionsinclude also support for non-portable systems as well.	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;=head2 How can I tell whether there's a character waiting on a filehandle?The very first thing you should do is look into getting the Term::ReadKeyextension from CPAN.  As we mentioned earlier, it now even has limitedsupport for non-portable (read: not open systems, closed, proprietary,not POSIX, not Unix, etc) systems.You should also check out the Frequently Asked Questions list incomp.unix.* for things like this: the answer is essentially the same.It's very system dependent.  Here's one solution that works on BSDsystems:	sub key_ready {		my($rin, $nfd);		vec($rin, fileno(STDIN), 1) = 1;		return $nfd = select($rin,undef,undef,0);		}If you want to find out how many characters are waiting, there'salso the FIONREAD ioctl call to be looked at.  The I<h2ph> tool thatcomes with Perl tries to convert C include files to Perl code, whichcan be C<require>d.  FIONREAD ends up defined as a function in theI<sys/ioctl.ph> file:	require 'sys/ioctl.ph';	$size = pack("L", 0);	ioctl(FH, FIONREAD(), $size)    or die "Couldn't call ioctl: $!\n";	$size = unpack("L", $size);If I<h2ph> wasn't installed or doesn't work for you, you canI<grep> the include files by hand:	% grep FIONREAD /usr/include/*/*	/usr/include/asm/ioctls.h:#define FIONREAD      0x541BOr write a small C program using the editor of champions:	% cat > fionread.c	#include <sys/ioctl.h>	main() {	    printf("%#08x\n", FIONREAD);	}	^D	% cc -o fionread fionread.c	% ./fionread	0x4004667fAnd then hard code it, leaving porting as an exercise to your successor.	$FIONREAD = 0x4004667f;         # XXX: opsys dependent	$size = pack("L", 0);	ioctl(FH, $FIONREAD, $size)     or die "Couldn't call ioctl: $!\n";	$size = unpack("L", $size);FIONREAD requires a filehandle connected to a stream, meaning that sockets,pipes, and tty devices work, but I<not> files.=head2 How do I do a C<tail -f> in perl?X<tail> X<IO::Handle> X<File::Tail> X<clearerr>First try	seek(GWFILE, 0, 1);The statement C<seek(GWFILE, 0, 1)> doesn't change the current position,but it does clear the end-of-file condition on the handle, so that thenext C<< <GWFILE> >> makes Perl try again to read something.If that doesn't work (it relies on features of your stdio implementation),then you need something more like this:	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	}If this still doesn't work, look into the C<clearerr> methodfrom C<IO::Handle>, which resets the error and end-of-file stateson the handle.There's also a C<File::Tail> module from CPAN.=head2 How do I dup() a filehandle in Perl?X<dup>If you check L<perlfunc/open>, you'll see that several of the waysto call open() should do the trick.  For example:	open(LOG, ">>/foo/logfile");	open(STDERR, ">&LOG");Or even with a literal numeric descriptor:   $fd = $ENV{MHCONTEXTFD};   open(MHCONTEXT, "<&=$fd");	# like fdopen(3S)Note that "<&STDIN" makes a copy, but "<&=STDIN" makean alias.  That means if you close an aliased handle, allaliases become inaccessible.  This is not true witha copied one.Error checking, as always, has been left as an exercise for the reader.=head2 How do I close a file descriptor by number?X<file, closing file descriptors> X<POSIX> X<close>If, for some reason, you have a file descriptor instead of afilehandle (perhaps you used C<POSIX::open>), you can use theC<close()> function from the C<POSIX> module:	use POSIX ();		POSIX::close( $fd );	This should rarely be necessary, as the Perl C<close()> function is to beused for things that Perl opened itself, even if it was a dup of anumeric descriptor as with C<MHCONTEXT> above.  But if you really haveto, you may be able to do this:	require 'sys/syscall.ph';	$rc = syscall(&SYS_close, $fd + 0);  # must force numeric	die "can't sysclose $fd: $!" unless $rc == -1;Or, just use the fdopen(3S) feature of C<open()>:	{	open my( $fh ), "<&=$fd" or die "Cannot reopen fd=$fd: $!";	close $fh;	}=head2 Why can't I use "C:\temp\foo" in DOS paths?  Why doesn't `C:\temp\foo.exe` work?X<filename, DOS issues>Whoops!  You just put a tab and a formfeed into that filename!Remember that within double quoted strings ("like\this"), thebackslash is an escape character.  The full list of these is inL<perlop/Quote and Quote-like Operators>.  Unsurprisingly, you don'thave a file called "c:(tab)emp(formfeed)oo" or"c:(tab)emp(formfeed)oo.exe" on your legacy DOS filesystem.Either single-quote your strings, or (preferably) use forward slashes.Since all DOS and Windows versions since something like MS-DOS 2.0 or sohave treated C</> and C<\> the same in a path, you might as well use theone that doesn't clash with Perl--or the POSIX shell, ANSI C and C++,awk, Tcl, Java, or Python, just to mention a few.  POSIX pathsare more portable, too.=head2 Why doesn't glob("*.*") get all the files?X<glob>Because even on non-Unix ports, Perl's glob function follows standardUnix globbing semantics.  You'll need C<glob("*")> to get all (non-hidden)files.  This makes glob() portable even to legacy systems.  Yourport may include proprietary globbing functions as well.  Check itsdocumentation for details.=head2 Why does Perl let me delete read-only files?  Why does C<-i> clobber protected files?  Isn't this a bug in Perl?This is elaborately and painstakingly described in theF<file-dir-perms> article in the "Far More Than You Ever Wanted ToKnow" collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz .The executive summary: learn how your filesystem works.  Thepermissions on a file say what can happen to the data in that file.The permissions on a directory say what can happen to the list offiles in that directory.  If you delete a file, you're removing itsname from the directory (so the operation depends on the permissionsof the directory, not of the file).  If you try to write to the file,the permissions of the file govern whether you're allowed to.=head2 How do I select a random line from a file?X<file, selecting a random line>Here's an algorithm from the Camel Book:	srand;	rand($.) < 1 && ($line = $_) while <>;This has a significant advantage in space over reading the whole filein.  You can find a proof of this method in I<The Art of ComputerProgramming>, Volume 2, Section 3.4.2, by Donald E. Knuth.You can use the File::Random module which provides a functionfor that algorithm:	use File::Random qw/random_line/;	my $line = random_line($filename);Another way is to use the Tie::File module, which treats the entirefile as an array.  Simply access a random array element.=head2 Why do I get weird spaces when I print an array of lines?Saying	print "@lines\n";joins together the elements of C<@lines> with a space between them.If C<@lines> were C<("little", "fluffy", "clouds")> then the abovestatement would print	little fluffy cloudsbut if each element of C<@lines> was a line of text, ending a newlinecharacter C<("little\n", "fluffy\n", "clouds\n")> then it would print:	little	 fluffy	 cloudsIf your array contains lines, just print them:	print @lines;=head1 REVISIONRevision: $Revision: 10126 $Date: $Date: 2007-10-27 21:29:20 +0200 (Sat, 27 Oct 2007) $See L<perlfaq> for source control details and availability.=head1 AUTHOR AND COPYRIGHTCopyright (c) 1997-2007 Tom Christiansen, Nathan Torkington, andother authors as noted. All rights reserved.This documentation is free; you can redistribute it and/or modify itunder the same terms as Perl itself.Irrespective of its distribution, all code examples here are in the publicdomain.  You are permitted and encouraged to use this code and anyderivatives thereof in your own programs for fun or for profit as yousee fit.  A simple comment in the code giving credit to the FAQ wouldbe courteous but is not required.

⌨️ 快捷键说明

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