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

📄 perlfaq5.pod

📁 ARM上的如果你对底层感兴趣
💻 POD
📖 第 1 页 / 共 3 页
字号:

If you prefer something more legible, use the File::stat module
(part of the standard distribution in version 5.004 and later):

    use File::stat;
    use Time::localtime;
    $date_string = ctime(stat($file)->mtime);
    print "file $file updated at $date_string\n";

Error checking is left as an exercise for the reader.

=head2 How do I set a file's timestamp in perl?

You use the utime() function documented in L<perlfunc/utime>.
By way of example, here's a little program that copies the
read and write times from its first argument to all the rest
of 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 left as an exercise for the reader.

Note that utime() currently doesn't work correctly with Win95/NT
ports.  A bug has been reported.  Check it carefully before using
it on those platforms.

=head2 How do I print to more than one file at once?

If you only have to do this once, you can do this:

    for $fh (FH1, FH2, FH3) { print $fh "whatever\n" }

To connect up to one filehandle to several output filehandles, it's
easiest to use the tee(1) program if you have it, and let it take care
of the multiplexing:

    open (FH, "| tee file1 file2 file3");

Or even:

    # make STDOUT go to three files, plus original STDOUT
    open (STDOUT, "| tee file1 file2 file3") or die "Teeing off: $!\n";
    print "whatever\n"                       or die "Writing: $!\n";
    close(STDOUT)                            or die "Closing: $!\n";

Otherwise you'll have to write your own multiplexing print
function -- or your own tee program -- or use Tom Christiansen's,
at http://www.perl.com/CPAN/authors/id/TOMC/scripts/tct.gz, which is
written in Perl and offers much greater functionality
than the stock version.

=head2 How can I read in a file by paragraphs?

Use the C<$\> variable (see L<perlvar> for details).  You can either
set it to C<""> to eliminate empty paragraphs (C<"abc\n\n\n\ndef">,
for instance, gets treated as two paragraphs and not three), or
C<"\n\n"> to accept empty paragraphs.

=head2 How can I read a single character from a file?  From the keyboard?

You can use the builtin C<getc()> function for most filehandles, but
it won't (easily) work on a terminal device.  For STDIN, either use
the Term::ReadKey module from CPAN, or use the sample code in
L<perlfunc/getc>.

If your system supports POSIX, you can use the following code, which
you'll note turns 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:

    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;

For DOS systems, Dan Carson <dbc@tc.fluke.COM> reports the following:

To put the PC in "raw" mode, use ioctl with some magic numbers gleaned
from msdos.c (Perl source file) and Ralf Brown's interrupt list (comes
across the net every so often):

    $old_ioctl = ioctl(STDIN,0,0);     # Gets device info
    $old_ioctl &= 0xff;
    ioctl(STDIN,1,$old_ioctl | 32);    # Writes it back, setting bit 5

Then to read a single character:

    sysread(STDIN,$c,1);               # Read a single character

And to put the PC back to "cooked" mode:

    ioctl(STDIN,1,$old_ioctl);         # Sets it back to cooked mode.

So now you have $c.  If C<ord($c) == 0>, you have a two byte code, which
means you hit a special key.  Read another byte with C<sysread(STDIN,$c,1)>,
and that value tells you what combination it was according to this
table:

    # PC 2-byte keycodes = ^@ + the following:

    # 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

This is all trial and error I did a long time ago, I hope I'm reading the
file that worked.

=head2 How can I tell if there's a character waiting on a filehandle?

The very first thing you should do is look into getting the Term::ReadKey
extension from CPAN.  It now even has limited support for closed, proprietary
(read: not open systems, not POSIX, not Unix, etc) systems.

You should also 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 BSD
systems:

    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's also the FIONREAD ioctl call to be looked at.

The I<h2ph> tool that comes with Perl tries to convert C include
files to Perl code, which can be C<require>d.  FIONREAD ends
up defined as a function in the I<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 can
I<grep> the include files by hand:

    % grep FIONREAD /usr/include/*/*
    /usr/include/asm/ioctls.h:#define FIONREAD      0x541B

Or 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
    % ./fionread
    0x4004667f

And 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 sockets,
pipes, and tty devices work, but I<not> files.

=head2 How do I do a C<tail -f> in perl?

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 the
next <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 POSIX module.  POSIX defines
the clearerr() method, which can remove the end of file condition on a
filehandle.  The method: read until end of file, clearerr(), read some
more.  Lather, rinse, repeat.

=head2 How do I dup() a filehandle in Perl?

If you check L<perlfunc/open>, you'll see that several of the ways
to call open() should do the trick.  For example:

    open(LOG, ">>/tmp/logfile");
    open(STDERR, ">&LOG");

Or even with a literal numeric descriptor:

   $fd = $ENV{MHCONTEXTFD};
   open(MHCONTEXT, "<&=$fd");	# like fdopen(3S)

Note that "E<lt>&STDIN" makes a copy, but "E<lt>&=STDIN" make
an alias.  That means if you close an aliased handle, all
aliases become inaccessible.  This is not true with 
a 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?

This should rarely be necessary, as the Perl close() function is to be
used for things that Perl opened itself, even if it was a dup of a
numeric descriptor, as with MHCONTEXT above.  But if you really have
to, 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;

=head2 Why can't I use "C:\temp\foo" in DOS paths?  What doesn't `C:\temp\foo.exe` work?

Whoops!  You just put a tab and a formfeed into that filename!
Remember that within double quoted strings ("like\this"), the
backslash is an escape character.  The full list of these is in
L<perlop/Quote and Quote-like Operators>.  Unsurprisingly, you don't
have a file called "c:(tab)emp(formfeed)oo" or
"c:(tab)emp(formfeed)oo.exe" on your 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 so
have treated C</> and C<\> the same in a path, you might as well use the
one that doesn't clash with Perl -- or the POSIX shell, ANSI C and C++,
awk, Tcl, Java, or Python, just to mention a few.

=head2 Why doesn't glob("*.*") get all the files?

Because even on non-Unix ports, Perl's glob function follows standard
Unix globbing semantics.  You'll need C<glob("*")> to get all (non-hidden)
files.  This makes glob() portable.

=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 the "Far More Than
You Ever Wanted To Know" in
http://www.perl.com/CPAN/doc/FMTEYEWTK/file-dir-perms .

The executive summary: learn how your filesystem works.  The
permissions 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 of
files in that directory.  If you delete a file, you're removing its
name from the directory (so the operation depends on the permissions
of 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?

Here's an algorithm from the Camel Book:

    srand;
    rand($.) < 1 && ($line = $_) while <>;

This has a significant advantage in space over reading the whole
file in.  A simple proof by induction is available upon 
request if you doubt its correctness.

=head1 AUTHOR AND COPYRIGHT

Copyright (c) 1997, 1998 Tom Christiansen and Nathan Torkington.
All rights reserved.

When included as an integrated part of the Standard Distribution
of Perl or of its documentation (printed or otherwise), this works is
covered under Perl's Artistic Licence.  For separate distributions of
all or part of this FAQ outside of that, see L<perlfaq>.

Irrespective of its distribution, all code examples here are public
domain.  You are permitted and encouraged to use this code and any
derivatives thereof in your own programs for fun or for profit as you
see fit.  A simple comment in the code giving credit to the FAQ would
be courteous but is not required.

⌨️ 快捷键说明

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