Seth Woolley's Man Viewer

perlfaq5(1) - perlfaq5 - Files and Formats ($Revision: 1.30 $, $Date: 2003/11/23 08:07:46 $) - man 1 perlfaq5

([section] manual, -k keyword, -K [section] search, -f whatis)
man plain no title

PERLFAQ5(1)            Perl Programmers Reference Guide            PERLFAQ5(1)

       perlfaq5 - Files and Formats ($Revision: 1.30 $, $Date: 2003/11/23
       08:07:46 $)

       This section deals with I/O and the "f" issues: filehandles, flushing,
       formats, and footers.

       How do I flush(8,n)/unbuffer an output filehandle?  Why must I do this?

       Perl does not support truly unbuffered output (except insofar as you
       can "syswrite(OUT, $char, 1)"), although it does support is "command
       buffering", in(1,8) which a physical write(1,2) is performed after every output

       The C standard I/O library (stdio) normally buffers characters sent to
       devices so that there isn't a system call for each byte. In most stdio
       implementations, the type of output buffering and the size of the
       buffer varies according to the type of device. Perl's print() and
       write(1,2)() functions normally buffer output, while syswrite() bypasses
       buffering all together.

       If you want your output to be sent immediately when you execute print()
       or write(1,2)() (for instance, for some network protocols), you must set(7,n,1 builtins) the
       handle's autoflush flag. This flag is the Perl variable $| and when it
       is set(7,n,1 builtins) to a true value, Perl will flush(8,n) the handle's buffer after each
       print() or write(1,2)(). Setting $| affects buffering only for the currently
       selected default file(1,n) handle. You choose this handle with the one argu-
       ment select(2,7,2 select_tut)() call (see "$|" in(1,8) perlvar and "select(2,7,2 select_tut)" in(1,8) perlfunc).

       Use select(2,7,2 select_tut)() to choose the desired handle, then set(7,n,1 builtins) its per-filehandle

           $old_fh = select(2,7,2 select_tut)(OUTPUT_HANDLE);
           $| = 1;
           select(2,7,2 select_tut)($old_fh);

       Some idioms can handle this in(1,8) a single statement:

           select(2,7,2 select_tut)((select(2,7,2 select_tut)(OUTPUT_HANDLE), $| = 1)[0]);

           $| = 1, select(2,7,2 select_tut) $_ for select(2,7,2 select_tut) OUTPUT_HANDLE;

       Some modules offer object-oriented access(2,5) to handles and their vari-
       ables, although they may be overkill if(3,n) this is the only thing you do
       with them.  You can use IO::Handle:

           use IO::Handle;
           open(2,3,n)(DEV, ">/dev/printer");   # but is this?

       or IO::Socket:

           use IO::Socket;               # this one is kinda a pipe(2,8)?
               my $sock = IO::Socket::INET->new( '' ) ;


       How do I change one line in(1,8) a file(1,n)/delete a line in(1,8) a file(1,n)/insert a
       line in(1,8) the middle of a file(1,n)/append to the beginning of a file(1,n)?

       Use the Tie::File module, which is included in(1,8) the standard distribu-
       tion since Perl 5.8.0.

       How do I count the number of lines in(1,8) a file(1,n)?

       One fairly efficient way is to count newlines in(1,8) the file. The follow-
       ing program uses a feature of tr///, as documented in(1,8) perlop.  If your
       text file(1,n) doesn't end with a newline, then it's not really a proper
       text file(1,n), so this may report one fewer line than you expect.

           $lines = 0;
           open(2,3,n)(FILE, $filename) or die "Can't open(2,3,n) `$filename': $!";
           while (sysread FILE, $buffer, 4096) {
               $lines += ($buffer =~ tr/\n//);
           close(2,7,n) FILE;

       This assumes no funny games with newline translations.

       How can I use Perl's "-i" option from within a program?

       "-i" sets the value of Perl's $^I variable, which in(1,8) turn affects the
       behavior of "<>"; see perlrun for more details.  By modifying the
       appropriate variables directly, you can get the same behavior within a
       larger program.  For example:

            # ...
               local($^I, @ARGV) = ('.orig', glob(1,3,7,n)("*.c"));
               while (<>) {
                  if(3,n) ($. == 1) {
                      print "This line should appear at the top of each file(1,n)\n";
                  s/\b(p)earl\b/${1}erl/i;        # Correct typos, preserving case
                  close(2,7,n) ARGV if(3,n) eof;              # Reset $.
            # $^I and @ARGV return to their old values here

       This block modifies all the ".c" files in(1,8) the current directory, leav-
       ing a backup of the original data from each file(1,n) in(1,8) a new ".c.orig"

       How do I make a temporary file(1,n) name?

       Use the File::Temp module, see File::Temp for more information.

         use File::Temp qw/ tempfile tempdir /;

         $dir = tempdir( CLEANUP => 1 );
         ($fh, $filename) = tempfile( DIR => $dir );

         # or if(3,n) you don't need to know the filename

         $fh = tempfile( DIR => $dir );

       The File::Temp has been a standard module since Perl 5.6.1.  If you
       don't have a modern enough Perl installed, use the "new_tmpfile" class
       method from the IO::File module to get a filehandle opened for reading
       and writing.  Use it if(3,n) you don't need to know the file(1,n)'s name:

           use IO::File;
           $fh = IO::File->new_tmpfile()
               or die "Unable to make new temporary file: $!";

       If you're committed to creating a temporary file(1,n) by hand, use the
       process ID and/or the current time-value.  If you need to have many
       temporary files in(1,8) one process, use a counter:

           BEGIN {
               use Fcntl;
               my $temp_dir = -d '/tmp' ? '/tmp' : $ENV{TMPDIR} || $ENV{TEMP};
               my $base_name = sprintf("%s/%d-%d-0000", $temp_dir, $$, time(1,2,n)());
               sub temp_file {
                   local *FH;
                   my $count = 0;
                   until (defined(fileno(FH)) || $count++ > 100) {
                       $base_name =~ s/-(\d+)$/"-" . (1 + $1)/e;
                       # O_EXCL is required for security reasons.
                       sysopen(FH, $base_name, O_WRONLY|O_EXCL|O_CREAT);
                   if(3,n) (defined(fileno(FH))
                       return (*FH, $base_name);
                   } else {
                       return ();

       How can I manipulate fixed-record-length files?

       The most efficient way is using pack(3,n,n pack-old)() and unpack().  This is faster
       than using substr() when taking many, many strings.  It is slower for
       just a few.

       Here is a sample chunk of code to break up and put back together again
       some fixed-format input lines, in(1,8) this case from the output of a nor-
       mal, Berkeley-style ps:

           # sample input line:
           #   15158 p5  T      0:00 perl /home/tchrist/scripts/now-what
           my $PS_T = 'A6 A4 A7 A5 A*';
           open(2,3,n) my $ps, '-|', 'ps';
           print scalar <$ps>;
           my @fields = qw( pid tt stat(1,2) time(1,2,n) command );
           while (<$ps>) {
               my %process;
               @process{@fields} = unpack($PS_T, $_);
               for my $field ( @fields ) {
                   print "$field: <$process{$field}>\n";
               print 'line=', pack(3,n,n pack-old)($PS_T, @process{@fields} ), "\n";

       We've used a hash slice in(1,8) order to easily handle the fields of each
       row.  Storing the keys in(1,8) an array means it's easy to operate on them
       as a group or loop over them with for. It also avoids polluting the
       program with global variables and using symbolic references.

       How can I make a filehandle local to a subroutine?  How do I pass file-
       handles between subroutines?  How do I make an array of filehandles?

       As of perl5.6, open(2,3,n)() autovivifies file(1,n) and directory handles as refer-
       ences if(3,n) you pass it an uninitialized scalar variable.  You can then
       pass these references just like any other scalar, and use them in(1,8) the
       place of named(5,8) handles.

               open(2,3,n) my    $fh, $file_name;

               open(2,3,n) local $fh, $file_name;

               print $fh "Hello World!\n";

               process_file( $fh );

       Before perl5.6, you had to deal with various typeglob idioms which you
       may see in(1,8) older code.

               open(2,3,n) FILE, "> $filename";
               process_typeglob(   *FILE );
               process_reference( \*FILE );

               sub process_typeglob  { local *FH = shift; print FH  "Typeglob!" }
               sub process_reference { local $fh = shift; print $fh "Reference!" }

       If you want to create many anonymous handles, you should check out the
       Symbol or IO::Handle modules.

       How can I use a filehandle indirectly?

       An indirect filehandle is using something other than a symbol in(1,8) a
       place that a filehandle is expected.  Here are ways to get indirect

           $fh =   SOME_FH;       # bareword is strict-subs hostile
           $fh =  "SOME_FH";      # strict-refs hostile; same package only
           $fh =  *SOME_FH;       # typeglob
           $fh = \*SOME_FH;       # ref to typeglob (bless-able)
           $fh =  *SOME_FH{IO};   # blessed IO::Handle from *SOME_FH typeglob

       Or, you can use the "new" method from one of the IO::* modules to cre-
       ate an anonymous filehandle, store that in(1,8) a scalar variable, and use
       it as though it were a normal filehandle.

           use IO::Handle;                     # 5.004 or higher
           $fh = IO::Handle->new();

       Then use any of those as you would a normal filehandle.  Anywhere that
       Perl is expecting a filehandle, an indirect filehandle may be used
       instead. An indirect filehandle is just a scalar variable that contains
       a filehandle.  Functions like "print", "open(2,3,n)", "seek", or the "<FH>"
       diamond operator will accept(2,8) either a named(5,8) filehandle or a scalar
       variable containing one:

           ($ifh, $ofh, $efh) = (*STDIN, *STDOUT, *STDERR);
           print $ofh "Type it: ";
           $got = <$ifh>
           print $efh "What was that: $got";

       If you're passing a filehandle to a function, you can write(1,2) the func-
       tion in(1,8) two ways:

           sub accept_fh {
               my $fh = shift;
               print $fh "Sending to indirect filehandle\n";

       Or it can localize a typeglob and use the filehandle directly:

           sub accept_fh {
               local *FH = shift;
               print  FH "Sending to localized filehandle\n";

       Both styles work with either objects or typeglobs of real filehandles.
       (They might also work with strings under some circumstances, but this
       is risky.)


       In the examples above, we assigned the filehandle to a scalar variable
       before using it.  That is because only simple scalar variables, not
       expressions or subscripts of hashes or arrays, can be used with built-
       ins like "print", "printf(1,3,1 builtins)", or the diamond operator.  Using something
       other than a simple scalar variable as a filehandle is illegal and
       won't even compile:

           @fd = (*STDIN, *STDOUT, *STDERR);
           print $fd[1] "Type it: ";                           # WRONG
           $got = <$fd[0]>                                     # WRONG
           print $fd[2] "What was that: $got";                 # WRONG

       With "print" and "printf(1,3,1 builtins)", you get around this by using a block and an
       expression where you would place the filehandle:

           print  { $fd[1] } "funny stuff\n";
           printf(1,3,1 builtins) { $fd[1] } "Pity the poor %x.\n", 3_735_928_559;
           # Pity the poor deadbeef.

       That block is a proper block like any other, so you can put more com-
       plicated code there.  This sends the message out to one of two places:

           $ok = -x "/bin/cat";
           print { $ok ? $fd[1] : $fd[2] } "cat stat(1,2) $ok\n";
           print { $fd[ 1+ ($ok || 0) ]  } "cat stat(1,2) $ok\n";

       This approach of treating "print" and "printf(1,3,1 builtins)" like object methods
       calls doesn't work for the diamond operator.  That's because it's a
       real operator, not just a function with a comma-less argument.  Assum-
       ing you've been storing typeglobs in(1,8) your structure as we did above,
       you can use the built-in function named(5,8) "readline" to read(2,n,1 builtins) a record
       just as "<>" does.  Given the initialization shown above for @fd, this
       would work, but only because readline() requires a typeglob.  It
       doesn't work with objects or strings, which might be a bug we haven't
       fixed yet.

           $got = readline($fd[0]);

       Let it be noted that the flakiness of indirect filehandles is not
       related to whether they're strings, typeglobs, objects, or anything
       else.  It's the syntax of the fundamental operators.  Playing the
       object game doesn't help you at all here.

       How can I set(7,n,1 builtins) up a footer format to be used with write(1,2)()?

       There's no builtin way to do this, but perlform has a couple of tech-
       niques to make it possible for the intrepid hacker.

       How can I write(1,2)() into a string(3,n)?

       See "Accessing Formatting Internals" in(1,8) perlform for an swrite() func-

       How can I output my numbers with commas added?

       This subroutine will add commas to your number:

               sub commify {
                  local $_  = shift;
                  1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
                  return $_;

       This regex(3,7) from Benjamin Goldberg will add commas to numbers:


       It is easier to see with comments:

              ^[-+]?            # beginning of number.
              \d{1,3}?          # first digits before first comma
              (?=               # followed by, (but not included in(1,8) the match) :
                 (?>(?:\d{3})+) # some positive multiple of three digits.
                 (?!\d)         # an *exact* multiple, not x * 3 + 1 or whatever.
             |                  # or:
              \G\d{3}           # after the last group, get three digits
              (?=\d)            # but they have to have more digits after them.

       How can I translate tildes (~) in(1,8) a filename?

       Use the <> (glob(1,3,7,n)()) operator, documented in(1,8) perlfunc.  Older versions
       of Perl require that you have a shell installed that groks tildes.
       Recent perl versions have this feature built in. The File::KGlob module
       (available from CPAN) gives more portable glob(1,3,7,n) functionality.

       Within Perl, you may use this directly:

               $filename =~ s{
                 ^ ~             # find a leading tilde
                 (               # save this in(1,8) $1
                     [^/]        # a non-slash character
                           *     # repeated 0 or more times (0 means me)
                     ? (getpwnam($1))[7]
                     : ( $ENV{HOME} || $ENV{LOGDIR} )

       How come when I open(2,3,n) a file(1,n) read-write it wipes it out?

       Because you're using something like this, which truncates the file(1,n) and
       then gives you read-write access:

           open(2,3,n)(FH, "+> /path/name");          # WRONG (almost always)

       Whoops.  You should instead use this, which will fail if(3,n) the file(1,n)
       doesn't exist.

           open(2,3,n)(FH, "+< /path/name");          # open(2,3,n) for update(7,n)

       Using ">" always clobbers or creates.  Using "<" never does either.
       The "+" doesn't change this.

       Here are examples of many kinds of file(1,n) opens.  Those using sysopen()
       all assume

           use Fcntl;

       To open(2,3,n) file(1,n) for reading:

           open(2,3,n)(FH, "< $path")                                 || die $!;
           sysopen(FH, $path, O_RDONLY)                        || die $!;

       To open(2,3,n) file(1,n) for writing, create new file(1,n) if(3,n) needed or else truncate(2,7)
       old file:

           open(2,3,n)(FH, "> $path") || die $!;
           sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT)        || die $!;
           sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT, 0666)  || die $!;

       To open(2,3,n) file(1,n) for writing, create new file(1,n), file(1,n) must not exist:

           sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT)         || die $!;
           sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT, 0666)   || die $!;

       To open(2,3,n) file(1,n) for appending, create if(3,n) necessary:

           open(2,3,n)(FH, ">> $path") || die $!;
           sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT)       || die $!;
           sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT, 0666) || die $!;

       To open(2,3,n) file(1,n) for appending, file(1,n) must exist:

           sysopen(FH, $path, O_WRONLY|O_APPEND)               || die $!;

       To open(2,3,n) file(1,n) for update(7,n), file(1,n) must exist:

           open(2,3,n)(FH, "+< $path")                                || die $!;
           sysopen(FH, $path, O_RDWR)                          || die $!;

       To open(2,3,n) file(1,n) for update(7,n), create file(1,n) if(3,n) necessary:

           sysopen(FH, $path, O_RDWR|O_CREAT)                  || die $!;
           sysopen(FH, $path, O_RDWR|O_CREAT, 0666)            || die $!;

       To open(2,3,n) file(1,n) for update(7,n), file(1,n) must not exist:

           sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT)           || die $!;
           sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT, 0666)     || die $!;

       To open(2,3,n) a file(1,n) without blocking, creating if(3,n) necessary:

           sysopen(FH, "/foo/somefile", O_WRONLY|O_NDELAY|O_CREAT)
                   or die "can't open(2,3,n) /foo/somefile: $!":

       Be warned that neither creation nor deletion of files is guaranteed to
       be an atomic operation over NFS.  That is, two processes might both
       successfully create or unlink(1,2) the same file(1,n)!  Therefore O_EXCL isn't as
       exclusive as you might wish.

       See also the new perlopentut if(3,n) you have it (new for 5.6).

       Why do I sometimes get an "Argument list too long" when I use <*>?

       The "<>" operator performs a globbing operation (see above).  In Perl
       versions earlier than v5.6.0, the internal glob(1,3,7,n)() operator forks csh(1)
       to do the actual glob(1,3,7,n) expansion, but csh can't handle more than 127
       items and so gives the error(8,n) message "Argument list too long".  People
       who installed tcsh as csh won't have this problem, but their users(1,5) may
       be surprised by it.

       To get around this, either upgrade to Perl v5.6.0 or later, do the glob(1,3,7,n)
       yourself with readdir(2,3)() and patterns, or use a module like File::KGlob,
       one that doesn't use the shell to do globbing.

       Is there a leak/bug in(1,8) glob(1,3,7,n)()?

       Due to the current implementation on some operating systems, when you
       use the glob(1,3,7,n)() function or its angle-bracket alias in(1,8) a scalar context,
       you may cause a memory leak and/or unpredictable behavior.  It's best
       therefore to use glob(1,3,7,n)() only in(1,8) list context.

       How can I open(2,3,n) a file(1,n) with a leading ">" or trailing blanks?

       Normally perl ignores trailing blanks in(1,8) filenames, and interprets cer-
       tain leading characters (or a trailing "|") to mean something special.

       The three argument form of open(2,3,n)() lets you specify the mode separately
       from the filename.  The open(2,3,n)() function treats special mode characters
       and whitespace in(1,8) the filename as literals

               open(2,3,n) FILE, "<", "  file(1,n)  ";  # filename is "   file(1,n)   "
               open(2,3,n) FILE, ">", ">file(1,n)";     # filename is ">file(1,n)"

       It may be a lot clearer to use sysopen(), though:

           use Fcntl;
           $badpath = "<<<something really wicked   ";
           sysopen (FH, $badpath, O_WRONLY | O_CREAT | O_TRUNC)
               or die "can't open(2,3,n) $badpath: $!";

       How can I reliably rename(1,2,n) a file(1,n)?

       If your operating system supports a proper mv(1) utility or its func-
       tional equivalent, this works:

           rename(1,2,n)($old, $new) or system("mv", $old, $new);

       It may be more portable to use the File::Copy module instead.  You just
       copy to the new file(1,n) to the new name (checking return values), then
       delete the old one.  This isn't really the same semantically as a
       rename(1,2,n)(), which preserves meta-information like permissions, time-
       stamps, inode info(1,5,n), etc.

       Newer versions of File::Copy export a move(3x,7,3x curs_move)() function.

       How can I lock a file(1,n)?

       Perl's builtin flock(1,2)() function (see perlfunc for details) will call
       flock(1,2)(2) if(3,n) that exists, fcntl(2) if(3,n) it doesn't (on perl version(1,3,5) 5.004
       and later), and lockf(3) if(3,n) neither of the two previous system calls
       exists.  On some systems, it may even use a different form of native
       locking.  Here are some gotchas with Perl's flock(1,2)():

       1   Produces a fatal error(8,n) if(3,n) none of the three system calls (or their
           close(2,7,n) equivalent) exists.

       2   lockf(3) does not provide shared locking, and requires that the
           filehandle be open(2,3,n) for writing (or appending, or read(2,n,1 builtins)/writing).

       3   Some versions of flock(1,2)() can't lock files over a network (e.g. on
           NFS file(1,n) systems), so you'd need to force the use of fcntl(2) when
           you build Perl.  But even this is dubious at best.  See the flock(1,2)
           entry of perlfunc and the INSTALL file(1,n) in(1,8) the source distribution
           for information on building Perl to do this.

           Two potentially non-obvious but traditional flock(1,2) semantics are
           that it waits indefinitely until the lock is granted, and that its
           locks are merely advisory.  Such discretionary locks are more flex-
           ible, but offer fewer guarantees.  This means that files locked
           with flock(1,2)() may be modified by programs that do not also use
           flock(1,2)().  Cars that stop for red lights get on well with each
           other, but not with cars that don't stop for red lights.  See the
           perlport manpage, your port's specific documentation, or your sys-
           tem-specific local manpages for details.  It's best to assume tra-
           ditional behavior if(3,n) you're writing portable programs.  (If you're
           not, you should as always feel perfectly free to write(1,2) for your own
           system's idiosyncrasies (sometimes called "features").  Slavish
           adherence to portability concerns shouldn't get in(1,8) the way of your
           getting your job done.)

           For more information on file(1,n) locking, see also "File Locking" in(1,8)
           perlopentut if(3,n) you have it (new for 5.6).

       Why can't I just open(2,3,n)(FH, ">file.lock")?

       A common bit of code NOT TO USE is this:

           sleep(1,3)(3) while -e "file.lock";      # PLEASE DO NOT USE
           open(2,3,n)(LCK, "> file.lock");           # THIS BROKEN CODE

       This is a classic race condition: you take two steps to do something
       which must be done in(1,8) one.  That's why computer hardware provides an
       atomic test-and-set instruction.   In theory, this "ought" to work:

           sysopen(FH, "file.lock", O_WRONLY|O_EXCL|O_CREAT)
                       or die "can't open(2,3,n)  file.lock: $!";

       except that lamentably, file(1,n) creation (and deletion) is not atomic over
       NFS, so this won't work (at least, not every time(1,2,n)) over the net.  Vari-
       ous schemes involving link(1,2)() have been suggested, but these tend to
       involve busy-wait, which is also subdesirable.

       I still don't get locking.  I just want to increment the number in(1,8) the
       file.  How can I do this?

       Didn't anyone ever tell you web-page hit counters were useless?  They
       don't count number of hits, they're a waste of time(1,2,n), and they serve
       only to stroke the writer's vanity.  It's better to pick a random(3,4,6) num-
       ber; they're more realistic.

       Anyway, this is what you can do if(3,n) you can't help yourself.

           use Fcntl qw(:DEFAULT :flock);
           sysopen(FH, "numfile", O_RDWR|O_CREAT)       or die "can't open(2,3,n) numfile: $!";
           flock(1,2)(FH, LOCK_EX)                           or die "can't flock(1,2) numfile: $!";
           $num = <FH> || 0;
           seek(FH, 0, 0)                               or die "can't rewind numfile: $!";
           truncate(2,7)(FH, 0)                              or die "can't truncate(2,7) numfile: $!";
           (print FH $num+1, "\n")                      or die "can't write(1,2) numfile: $!";
           close(2,7,n) FH                                     or die "can't close(2,7,n) numfile: $!";

       Here's a much better web-page hit counter:

           $hits = int( (time(1,2,n)() - 850_000_000) / rand(1,3)(1_000) );

       If the count doesn't impress your friends, then the code might.  :-)

       All I want to do is append a small amount of text to the end of a file.
       Do I still have to use locking?

       If you are on a system that correctly implements flock(1,2)() and you use
       the example appending code from "perldoc -f flock(1,2)" everything will be
       OK even if(3,n) the OS you are on doesn't implement append mode correctly
       (if(3,n) such a system exists.) So if(3,n) you are happy to restrict yourself to
       OSs that implement flock(1,2)() (and that's not really much of a restric-
       tion) then that is what you should do.

       If you know you are only going to use a system that does correctly
       implement appending (i.e. not Win32) then you can omit the seek() from
       the above code.

       If you know you are only writing code to run on an OS and filesystem
       that does implement append mode correctly (a local filesystem on a mod-
       ern Unix for example), and you keep the file(1,n) in(1,8) block-buffered mode and
       you write(1,2) less(1,3) than one buffer-full of output between each manual
       flushing of the buffer then each bufferload is almost guaranteed to be
       written to the end of the file(1,n) in(1,8) one chunk without getting intermin-
       gled with anyone else's output. You can also use the syswrite() func-
       tion which is simply a wrapper around your systems write(1,2)(2) system

       There is still a small theoretical chance that a signal(2,7) will interrupt
       the system level write(1,2)() operation before completion.  There is also a
       possibility that some STDIO implementations may call multiple system
       level write(1,2)()s even if(3,n) the buffer was empty to start.  There may be
       some systems where this probability is reduced to zero.

       How do I randomly update(7,n) a binary file(1,n)?

       If you're just trying to patch a binary, in(1,8) many cases something as
       simple as this works:

           perl -i -pe 's{window manager}{window mangler}g' /usr/bin/emacs

       However, if(3,n) you have fixed sized records, then you might do something
       more like this:

           $RECSIZE = 220; # size of record, in(1,8) bytes
           $recno   = 37;  # which record to update(7,n)
           open(2,3,n)(FH, "+<somewhere") || die "can't update(7,n) somewhere: $!";
           seek(FH, $recno * $RECSIZE, 0);
           read(2,n,1 builtins)(FH, $record, $RECSIZE) == $RECSIZE || die "can't read(2,n,1 builtins) record $recno: $!";
           # munge the record
           seek(FH, -$RECSIZE, 1);
           print FH $record;
           close(2,7,n) FH;

       Locking and error(8,n) checking are left as an exercise for the reader.
       Don't forget them or you'll be quite sorry.

       How do I get a file(1,n)'s timestamp in(1,8) perl?

       If you want to retrieve the time(1,2,n) at which the file(1,n) was last read(2,n,1 builtins), writ-
       ten, or had its meta-data (owner, etc) changed, you use the -M, -A, or
       -C file(1,n) test operations as documented in(1,8) perlfunc.  These retrieve the
       age of the file(1,n) (measured against the start-time of your program) in(1,8)
       days as a floating point number. Some platforms may not have all of
       these times.  See perlport for details. To retrieve the "raw(3x,7,8,3x cbreak)" time(1,2,n) in(1,8)
       seconds since the epoch, you would call the stat(1,2) function, then use
       localtime(), gmtime(), or POSIX::strftime() to convert this into human-
       readable form.

       Here's an example:

           $write_secs = (stat(1,2)($file(1,n)))[9];
           printf(1,3,1 builtins) "file(1,n) %s updated at %s\n", $file(1,n),
               scalar localtime($write_secs);

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

           # error(8,n) checking left as an exercise for reader.
           use File::stat;
           use Time::localtime;
           $date_string = ctime(stat(1,2)($file(1,n))->mtime);
           print "file(1,n) $file(1,n) updated at $date_string\n";

       The POSIX::strftime() approach has the benefit of being, in(1,8) theory,
       independent of the current locale.  See perllocale for details.

       How do I set(7,n,1 builtins) a file(1,n)'s timestamp in(1,8) perl?

       You use the utime() function documented in(1,8) "utime" in(1,8) perlfunc.  By way
       of example, here's a little program that copies the read(2,n,1 builtins) and write(1,2)
       times from its first argument to all the rest of them.

           if(3,n) (@ARGV < 2) {
               die "usage: cptimes timestamp_file other_files ...\n";
           $timestamp = shift;
           ($atime, $mtime) = (stat(1,2)($timestamp))[8,9];
           utime $atime, $mtime, @ARGV;

       Error checking is, as usual, 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 utime() on
       those platforms.

       How do I print to more than one file(1,n) at once?

       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 individually to each

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

       How can I read(2,n,1 builtins) in(1,8) an entire file(1,n) all at once?

       You can use the File::Slurp module to do it in(1,8) one step.

               use File::Slurp;

               $all_of_it = read_file($filename); # entire file(1,n) in(1,8) scalar
           @all_lines = read_file($filename); # one line perl element

       The customary Perl approach for processing all the lines in(1,8) a file(1,n) is
       to do so one line at a time:

           open(2,3,n) (INPUT, $file(1,n))         || die "can't open(2,3,n) $file: $!";
           while (<INPUT>) {
               # do something with $_
           close(2,7,n)(INPUT)                || die "can't close(2,7,n) $file: $!";

       This is tremendously more efficient than reading the entire file(1,n) into
       memory as an array of lines and then processing it one element at a
       time(1,2,n), which is often--if not almost always--the wrong approach.  When-
       ever you see someone do this:

           @lines = <INPUT>;

       you should think long and hard about why you need everything loaded at
       once.  It's just not a scalable solution.  You might also find it more
       fun 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(1,n) so that
       accessing an element the array actually accesses the corresponding line
       in(1,8) the file.

       You can read(2,n,1 builtins) the entire filehandle contents into a scalar.

               local(*INPUT, $/);
               open(2,3,n) (INPUT, $file(1,n))     || die "can't open(2,3,n) $file: $!";
               $var = <INPUT>;

       That temporarily undefs your record separator, and will automatically
       close(2,7,n) the file(1,n) at block exit.  If the file(1,n) is already open(2,3,n), just use

           $var = do { local $/; <INPUT> };

       For ordinary files you can also use the read(2,n,1 builtins) function.

               read(2,n,1 builtins)( INPUT, $var, -s INPUT );

       The third argument tests the byte size of the data on the INPUT file-
       handle and reads that many bytes into the buffer $var.

       How can I read(2,n,1 builtins) in(1,8) a file(1,n) by paragraphs?

       Use the $/ variable (see perlvar for details).  You can either set(7,n,1 builtins) it
       to "" to eliminate empty paragraphs ("abc\n\n\n\ndef", for instance,
       gets(3,n) treated as two paragraphs and not three), or "\n\n" to accept(2,8)
       empty paragraphs.

       Note that a blank line must have no blanks in(1,8) it.  Thus
       "fred\n \nstuff\n\n" is one paragraph, but "fred\n\nstuff\n\n" is two.

       How can I read(2,n,1 builtins) a single character from a file(1,n)?  From the keyboard?

       You can use the builtin "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(1,8) "getc" in(1,8)

       If your system supports the portable operating system programming
       interface (POSIX), you can use the following code, which you'll note
       turns off echo(1,3x,1 builtins) processing as well.

           #!/usr/bin/perl -w
           use strict;
           $| = 1;
           for (1..4) {
               my $got;
               print "gimme: ";
               $got = getone();
               print "--> $got\n";
           exit(3,n,1 builtins);

           BEGIN {
               use POSIX qw(:termios_h);

               my ($term(5,7), $oterm, $echo(1,3x,1 builtins), $noecho, $fd_stdin);

               $fd_stdin = fileno(STDIN);

               $term(5,7)     = POSIX::Termios->new();
               $oterm     = $term->getlflag();

               $echo(1,3x,1 builtins)     = ECHO | ECHOK | ICANON;
               $noecho   = $oterm & ~$echo(1,3x,1 builtins);

               sub cbreak {
                   $term->setcc(VTIME, 1);
                   $term->setattr($fd_stdin, TCSANOW);

               sub cooked {
                   $term->setcc(VTIME, 0);
                   $term->setattr($fd_stdin, TCSANOW);

               sub getone {
                   my $key = '';
                   sysread(STDIN, $key, 1);
                   return $key;


           END { cooked() }

       The Term::ReadKey module from CPAN may be easier to use.  Recent ver-
       sions include also support for non-portable systems as well.

           use Term::ReadKey;
           open(2,3,n)(TTY, "</dev/tty(1,4)");
           print "Gimme a char: ";
           ReadMode "raw(3x,7,8,3x cbreak)";
           $key = ReadKey 0, *TTY;
           ReadMode "normal";
           printf(1,3,1 builtins) "\nYou said %s, char number %03d\n",
               $key, ord $key;

       How can I tell whether there's a character waiting on a filehandle?

       The very first thing you should do is look(1,8,3 Search::Dict) into getting the Term::Read-
       Key extension from CPAN.  As we mentioned earlier, it now even has lim-
       ited support for non-portable (read: not open(2,3,n) systems, closed, propri-
       etary, not POSIX, not Unix, etc) systems.

       You should also check out the Frequently Asked Questions list in(1,8)
       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 sys-

           sub key_ready {
               my($rin, $nfd);
               vec($rin, fileno(STDIN), 1) = 1;
               return $nfd = select(2,7,2 select_tut)($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 h2ph tool that comes with
       Perl tries to convert C include files to Perl code, which can be
       "require"d.  FIONREAD ends up defined as a function in(1,8) the sys/

           require 'sys/';

           $size = pack(3,n,n pack-old)("L", 0);
           ioctl(FH, FIONREAD(), $size)    or die "Couldn't call ioctl: $!\n";
           $size = unpack("L", $size);

       If h2ph wasn't installed or doesn't work for you, you can grep the
       include files by hand:

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

       Or write(1,2) a small C program using the editor of champions:

           % cat > fionread.c
           #include <sys/ioctl.h>
           main() {
               printf(1,3,1 builtins)("%#08x\n", FIONREAD);
           % cc -o fionread fionread.c
           % ./fionread

       And then hard code it, leaving porting as an exercise to your succes-

           $FIONREAD = 0x4004667f;         # XXX: opsys dependent

           $size = pack(3,n,n pack-old)("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(1,4) devices work, but not files.

       How do I do a "tail -f" in(1,8) perl?

       First try

           seek(GWFILE, 0, 1);

       The statement "seek(GWFILE, 0, 1)" doesn't change the current position,
       but it does clear(1,3x,3x clrtobot) the end-of-file condition on the handle, so that the
       next <GWFILE> makes Perl try again to read(2,n,1 builtins) something.

       If that doesn't work (it relies on features of your stdio implementa-
       tion), 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(1,3) for a while
                 seek(GWFILE, $curpos, 0);  # seek to where we had been

       If this still doesn't work, look(1,8,3 Search::Dict) into the POSIX module.  POSIX defines
       the clearerr() method, which can remove the end of file(1,n) condition on a
       filehandle.  The method: read(2,n,1 builtins) until end of file(1,n), clearerr(), read(2,n,1 builtins) some
       more.  Lather, rinse, repeat.

       There's also a File::Tail module from CPAN.

       How do I dup() a filehandle in(1,8) Perl?

       If you check "open(2,3,n)" in(1,8) perlfunc, you'll see that several of the ways to
       call open(2,3,n)() should do the trick.  For example:

           open(2,3,n)(LOG, ">>/foo/logfile");
           open(2,3,n)(STDERR, ">&LOG");

       Or even with a literal numeric descriptor:

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

       Note that "<&STDIN" makes a copy, but "<&=STDIN" make an alias.  That
       means if(3,n) you close(2,7,n) 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.

       How do I close(2,7,n) a file(1,n) descriptor by number?

       This should rarely be necessary, as the Perl close(2,7,n)() function is to be
       used for things that Perl opened itself, even if(3,n) it was a dup of a
       numeric descriptor as with MHCONTEXT above.  But if(3,n) you really have to,
       you may be able to do this:

           require 'sys/';
           $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 open(2,3,n)():

               local *F;
               open(2,3,n) F, "<&=$fd" or die "Cannot reopen fd=$fd: $!";
               close(2,7,n) F;

       Why can't I use "C:\temp\foo" in(1,8) DOS paths?  Why doesn't
       `C:\temp\foo.exe` work?

       Whoops!  You just put a tab and a formfeed into that filename!  Remem-
       ber that within double quoted strings ("like\this"), the backslash is
       an escape character.  The full list of these is in(1,8) "Quote and Quote-
       like Operators" in(1,8) perlop.  Unsurprisingly, you don't have a file(1,n)
       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
       so have treated "/" and "\" the same in(1,8) 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.  POSIX paths are
       more portable, too.

       Why doesn't glob(1,3,7,n)("*.*") get all the files?

       Because even on non-Unix ports, Perl's glob(1,3,7,n) function follows standard
       Unix globbing semantics.  You'll need "glob(1,3,7,n)("*")" to get all (non-hid-
       den) files.  This makes glob(1,3,7,n)() portable even to legacy systems.  Your
       port may include proprietary globbing functions as well.  Check its
       documentation for details.

       Why does Perl let me delete read-only files?  Why does "-i" clobber
       protected files?  Isn't this a bug in(1,8) Perl?

       This is elaborately and painstakingly described in(1,8) the file-dir-perms
       article in(1,8) the "Far More Than You Ever Wanted To Know" collection in(1,8) .

       The executive summary: learn how your filesystem works.  The permis-
       sions on a file(1,n) say what can happen to the data in(1,8) that file.  The per-
       missions on a directory say what can happen to the list of files in(1,8)
       that directory.  If you delete a file(1,n), you're removing its name from
       the directory (so the operation depends on the permissions of the
       directory, not of the file(1,n)).  If you try to write(1,2) to the file(1,n), the per-
       missions of the file(1,n) govern whether you're allowed to.

       How do I select(2,7,2 select_tut) a random(3,4,6) line from a file(1,n)?

       Here's an algorithm from the Camel Book:

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

       This has a significant advantage in(1,8) space over reading the whole file(1,n)
       in.  You can find a proof of this method in(1,8) The Art of Computer Pro-
       gramming, Volume 2, Section 3.4.2, by Donald E. Knuth.

       You can use the File::Random module which provides a function for that

               use File::Random qw/random_line/;
               my $line = random_line($filename);

       Another way is to use the Tie::File module, which treats the entire
       file(1,n) as an array.  Simply access(2,5) a random(3,4,6) array element.

       Why do I get weird spaces when I print an array of lines?


           print "@lines\n";

       joins together the elements of @lines with a space between them.  If
       @lines were "("little", "fluffy", "clouds")" then the above statement
       would print

           little fluffy clouds

       but if(3,n) each element of @lines was a line of text, ending a newline
       character "("little\n", "fluffy\n", "clouds\n")" then it would print:


       If your array contains lines, just print them:

           print @lines;

       Copyright (c) 1997-2002 Tom Christiansen and Nathan Torkington.  All
       rights reserved.

       This documentation is free; you can redistribute it and/or modify it
       under the same terms as Perl itself.

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

perl v5.8.5                       2004-04-23                       PERLFAQ5(1)

References for this manual (incoming links)