[comp.lang.perl] Editing in-place a binary file

lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (10/31/90)

In article <fuchs.657312322@t5000> fuchs@it.uka.de (Harald Fuchs) writes:
: The One True Manual Page sez:
:   -iextension
:        specifies that files processed by the <> construct are to be
:        edited in-place.
: This works fine if you read your files via "while (<>) { ... }",
: but what about binary files you'd like to read via "read (??, $var, $size)"?
: What filehandle must be used? I tried STDIN and ARGV, but nothing worked.

-i only works with while (<>).  But you can use while (<>) on a binary file--
you just get odd sized hunks, which is okay if you're just doing s///.  You
can change $/ to something that doesn't exist in the pattern you're looking
for.  You can even undef it and do each file in one slurp.

If you want to edit in-place with read (a situation that doesn't arise often
enough to support, in my estimation), you have to do it explicitly.  Generally
you just open the file, rename the currently open file to the backup name,
and then open the output file with the original name.  If you want to preserve
any hard links to the file, you have to REALLY edit the file in place, which
you can do by mixing reads and prints (or, nowadays, sysreads and syswrites)
on the same filehandle.  A backup would then have to be made by copying (don't
forget to copy the utimes).

Bear in mind that if you want to do s/pat/repl/ on a file, using read or
sysread can make your pattern span a buffer boundary.  Thus, while (<>) is
preferred in this case.

Larry

fuchs@it.uka.de (Harald Fuchs) (10/31/90)

The One True Manual Page sez:
  -iextension
       specifies that files processed by the <> construct are to be
       edited in-place.
This works fine if you read your files via "while (<>) { ... }",
but what about binary files you'd like to read via "read (??, $var, $size)"?
What filehandle must be used? I tried STDIN and ARGV, but nothing worked.
--

Harald Fuchs <fuchs@it.uka.de> <fuchs%it.uka.de@relay.cs.net> ...
<fuchs@telematik.informatik.uni-karlsruhe.dbp.de>   *gulp*