perlfaq5 - Files and Formats ($Revision: 10126 $)
This section deals with I/O and the "f" issues: filehandles, flushing,
formats, and footers.
Perl does not support truly unbuffered output (except insofar as you
can syswrite(OUT, $char, 1)), although it does support is "command
buffering", in which a physical write is performed after every output
command.
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() 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() (for instance, for some network protocols),
you must set the handle's autoflush flag. This flag is the Perl
variable $| and when it is set to a true value, Perl will flush the
handle's buffer after each print() or write(). Setting $|
affects buffering only for the currently selected default filehandle.
You choose this handle with the one argument select() call (see
$| in the perlvar manpage and select in the perlfunc manpage).
Use select() to choose the desired handle, then set its
per-filehandle variables.
$old_fh = select(OUTPUT_HANDLE);
$| = 1;
select($old_fh);
Some modules offer object-oriented access to handles and their
variables, although they may be overkill if this is the only thing you
do with them. You can use IO::Handle:
use IO::Handle;
open my( $printer ), ">", "/dev/printer");
$printer->autoflush(1);
or IO::Socket (which inherits from IO::Handle):
use IO::Socket;
my $sock = IO::Socket::INET->new( 'www.example.com:80' );
$sock->autoflush();
You can also flush an IO::Handle object without setting
autoflush. Call the flush method to flush the buffer yourself:
use IO::Handle;
open my( $printer ), ">", "/dev/printer");
$printer->flush;
(contributed by brian d foy)
The basic idea of inserting, changing, or deleting a line from a text
file involves reading and printing the file to the point you want to
make the change, making the change, then reading and printing the rest
of the file. Perl doesn't provide random access to lines (especially
since the record input separator, $/, is mutable), although modules
such as Tie::File can fake it.
A Perl program to do these tasks takes the basic form of opening a
file, printing its lines, then closing the file:
open my $in, '<', $file or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";
while( <$in> )
{
print $out $_;
}
close $out;
Within that basic form, add the parts that you need to insert, change,
or delete lines.
To prepend lines to the beginning, print those lines before you enter
the loop that prints the existing lines.
open my $in, '<', $file or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";
print "# Add this line to the top\n";
while( <$in> )
{
print $out $_;
}
close $out;
To change existing lines, insert the code to modify the lines inside
the while loop. In this case, the code finds all lowercased
versions of "perl" and uppercases them. The happens for every line, so
be sure that you're supposed to do that on every line!
open my $in, '<', $file or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";
print "# Add this line to the top\n";
while( <$in> )
{
s/\b(perl)\b/Perl/g;
print $out $_;
}
close $out;
To change only a particular line, the input line number, $., is
useful. First read and print the lines up to the one you want to
change. Next, read the single line you want to change, change it, and
print it. After that, read the rest of the lines and print those:
while( <$in> )
{
print $out $_;
last if $. == 4;
}
my $line = <$in>;
$line =~ s/\b(perl)\b/Perl/g;
print $out $line;
while( <$in> )
{
print $out $_;
}
To skip lines, use the looping controls. The C<next> in this example
skips comment lines, and the C<last> stops all processing once it
encounters either C<
while( <$in> )
{
next if /^\s+#/;
last if /^__(END|DATA)__$/;
print $out $_;
}
Do the same sort of thing to delete a particular line by using next
to skip the lines you don't want to show up in the output. This
example skips every fifth line:
while( <$in> )
{
next unless $. % 5;
print $out $_;
}
If, for some odd reason, you really want to see the whole file at once
rather than processing line by line, you can slurp it in (as long as
you can fit the whole thing in memory!):
open my $in, '<', $file or die "Can't read old file: $!"
open my $out, '>', "$file.new" or die "Can't write new file: $!";
my @lines = do { local $/; <$in> };
print $out @lines;
Modules such as File::Slurp and Tie::File can help with that
too. If you can, however, avoid reading the entire file at once. Perl
won't give that memory back to the operating system until the process
finishes.
You can also use Perl one-liners to modify a file in-place. The
following changes all 'Fred' to 'Barney' in inFile.txt, overwriting
the file with the new contents. With the -p switch, Perl wraps a
while loop around the code you specify with -e, and -i turns
on in-place editing. The current line is in $_. With -p, Perl
automatically prints the value of $_ at the end of the loop. See
the perlrun manpage for more details.
perl -pi -e 's/Fred/Barney/' inFile.txt
To make a backup of inFile.txt, give -i a file extension to add:
perl -pi.bak -e 's/Fred/Barney/' inFile.txt
To change only the fifth line, you can add a test checking $., the
input line number, then only perform the operation when the test
passes:
perl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt
To add lines before a certain line, you can add a line (or lines!)
before Perl prints $_:
perl -pi -e 'print "Put before third line\n" if $. == 3' inFile.txt
You can even add a line to the beginning of a file, since the current
line prints at the end of the loop:
perl -pi -e 'print "Put before first line\n" if $. == 1' inFile.txt
To insert a line after one already in the file, use the -n switch.
It's just like -p except that it doesn't print $_ at the end of
the loop, so you have to do that yourself. In this case, print $_
first, then print the line that you want to add.
perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt
To delete lines, only print the ones that you want.
perl -ni -e 'print unless /d/' inFile.txt
... or ...
perl -pi -e 'next unless /d/' inFile.txt
One fairly efficient way is to count newlines in the file. The
following program uses a feature of tr///, as documented in the perlop manpage.
If your text file doesn't end with a newline, then it's not really a
proper text file, so this may report one fewer line than you expect.
$lines = 0;
open(FILE, $filename) or die "Can't open `$filename': $!";
while (sysread FILE, $buffer, 4096) {
$lines += ($buffer =~ tr/\n//);
}
close FILE;
This assumes no funny games with newline translations.
-i sets the value of Perl's $^I variable, which in turn affects
the behavior of <>; see the perlrun manpage 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("*.c"));
while (<>) {
if ($. == 1) {
print "This line should appear at the top of each file\n";
}
s/\b(p)earl\b/${1}erl/i;
print;
close ARGV if eof;
}
}
This block modifies all the .c files in the current directory,
leaving a backup of the original data from each file in a new
.c.orig file.
(contributed by brian d foy)
Use the File::Copy module. It comes with Perl and can do a
true copy across file systems, and it does its magic in
a portable fashion.
use File::Copy;
copy( $original, $new_copy ) or die "Copy failed: $!";
If you can't use File::Copy, you'll have to do the work yourself:
open the original file, open the destination file, then print
to the destination file as you read the original.
If you don't need to know the name of the file, you can use open()
with undef in place of the file name. The open() function
creates an anonymous temporary file.
open my $tmp, '+>', undef or die $!;
Otherwise, you can use the File::Temp module.
use File::Temp qw/ tempfile tempdir /;
$dir = tempdir( CLEANUP => 1 );
($fh, $filename) = tempfile( DIR => $dir );
$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 you don't need to know the file'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 by hand, use the
process ID and/or the current time-value. If you need to have many
temporary files in 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;
sub temp_file {
local *FH;
my $count = 0;
until( defined(fileno(FH)) || $count++ > 100 ) {
$base_name =~ s/-(\d+)$/"-" . (1 + $1)/e;
sysopen FH, $base_name, O_WRONLY|O_EXCL|O_CREAT;
}
if( defined fileno(FH) ) {
return (*FH, $base_name);
}
else {
return ();
}
}
}
The most efficient way is using pack() 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 this case from the output of a normal,
Berkeley-style ps:
my $PS_T = 'A6 A4 A7 A5 A*';
open my $ps, '-|', 'ps';
print scalar <$ps>;
my @fields = qw( pid tt stat time command );
while (<$ps>) {
my %process;
@process{@fields} = unpack($PS_T, $_);
for my $field ( @fields ) {
print "$field: <$process{$field}>\n";
}
print 'line=', pack($PS_T, @process{@fields} ), "\n";
}
We've used a hash slice in order to easily handle the fields of each row.
Storing the keys in 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.
As of perl5.6, open() autovivifies file and directory handles
as references if you pass it an uninitialized scalar variable.
You can then pass these references just like any other scalar,
and use them in the place of named handles.
open my $fh, $file_name;
open local $fh, $file_name;
print $fh "Hello World!\n";
process_file( $fh );
If you like, you can store these filehandles in an array or a hash.
If you access them directly, they aren't simple scalars and you
need to give print a little help by placing the filehandle
reference in braces. Perl can only figure it out on its own when
the filehandle reference is a simple scalar.
my @fhs = ( $fh1, $fh2, $fh3 );
for( $i = 0; $i <= $#fhs; $i++ ) {
print {$fhs[$i]} "just another Perl answer, \n";
}
Before perl5.6, you had to deal with various typeglob idioms
which you may see in older code.
open 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.
An indirect filehandle is using something other than a symbol
in a place that a filehandle is expected. Here are ways
to get indirect filehandles:
$fh = SOME_FH;
$fh = "SOME_FH";
$fh = *SOME_FH;
$fh = \*SOME_FH;
$fh = *SOME_FH{IO};
Or, you can use the new method from one of the IO::* modules to
create an anonymous filehandle, store that in a scalar variable,
and use it as though it were a normal filehandle.
use IO::Handle;
$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, seek, or
the <FH> diamond operator will accept either a named 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
the function in 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.)
accept_fh(*STDOUT);
accept_fh($handle);
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, 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: ";
$got = <$fd[0]>
print $fd[2] "What was that: $got";
With print and printf, you get around this by using a block and
an expression where you would place the filehandle:
print { $fd[1] } "funny stuff\n";
printf { $fd[1] } "Pity the poor %x.\n", 3_735_928_559;
That block is a proper block like any other, so you can put more
complicated code there. This sends the message out to one of two places:
$ok = -x "/bin/cat";
print { $ok ? $fd[1] : $fd[2] } "cat stat $ok\n";
print { $fd[ 1+ ($ok || 0) ] } "cat stat $ok\n";
This approach of treating print and printf 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. Assuming
you've been storing typeglobs in your structure as we did above, you
can use the built-in function named readline to read 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.
There's no builtin way to do this, but the perlform manpage has a couple of
techniques to make it possible for the intrepid hacker.
See Accessing Formatting Internals in the perlform manpage for an swrite() function.
(contributed by Peter J. Holzer, hjp-usenet2@hjp.at)
Since Perl 5.8.0, you can pass a reference to a scalar instead of the
filename to create a file handle which you can used to read from or write to
a string:
open(my $fh, '>', \$string) or die "Could not open string for writing";
print $fh "foo\n";
print $fh "bar\n";
open(my $fh, '<', \$string) or die "Could not open string for reading";
my $x = <$fh>;
With older versions of Perl, the IO::String module provides similar
functionality.
(contributed by brian d foy and Benjamin Goldberg)
You can use the Number::Format manpage to separate places in a number.
It handles locale information for those of you who want to insert
full stops instead (or anything else that they want to use,
really).
This subroutine will add commas to your number:
sub commify {
local $_ = shift;
1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
return $_;
}
This regex from Benjamin Goldberg will add commas to numbers:
s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g;
It is easier to see with comments:
s/(
^[-+]? # beginning of number.
\d+? # first digits before first comma
(?= # followed by, (but not included in 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.
)/$1,/xg;
Use the <> (glob()) operator, documented in the perlfunc manpage. 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
functionality.
Within Perl, you may use this directly:
$filename =~ s{
^ ~ # find a leading tilde
( # save this in $1
[^/] # a non-slash character
* # repeated 0 or more times (0 means me)
)
}{
$1
? (getpwnam($1))[7]
: ( $ENV{HOME} || $ENV{LOGDIR} )
}ex;
Because you're using something like this, which truncates the file and
then gives you read-write access:
open(FH, "+> /path/name");
Whoops. You should instead use this, which w |