ASPN ActiveState Programmer Network
  ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups | Web Services
SEARCH
advanced | search help

Reference
ActivePerl 5.10
Core Documentation
perl
perlintro
perltoc
perlreftut
perldsc
perllol
perlrequick
perlretut
perlboot
perltoot
perltooc
perlbot
perlstyle
perlcheat
perltrap
perldebtut
perlfaq
perlfaq1
perlfaq2
perlfaq3
perlfaq4
perlfaq5
perlfaq6
perlfaq7
perlfaq8
perlfaq9
perlsyn
perldata
perlop
perlsub
perlfunc
perlopentut
perlpacktut
perlpod
perlpodspec
perlrun
perldiag
perllexwarn
perldebug
perlvar
perlre
perlrebackslash
perlrecharclass
perlreref
perlref
perlform
perlobj
perltie
perldbmfilter
perlipc
perlfork
perlnumber
perlthrtut
perlothrtut
perlport
perllocale
perluniintro
perlunicode
perlunifaq
perlunitut
perlebcdic
perlsec
perlmod
perlmodlib
perlmodstyle
perlmodinstall
perlnewmod
perlpragma
perlutil
perlcompile
perlfilter
perlglossary
perlembed
perldebguts
perlxstut
perlxs
perlclib
perlguts
perlcall
perlreapi
perlreguts
perlapi
perlintern
perliol
perlapio
perlhack
perlbook
perlcommunity
perltodo
perldoc
perlhist
perldelta
perl5100delta
perl595delta
perl594delta
perl593delta
perl592delta
perl591delta
perl590delta
perl588delta
perl587delta
perl586delta
perl585delta
perl584delta
perl583delta
perl582delta
perl581delta
perl58delta
perl573delta
perl572delta
perl571delta
perl570delta
perl561delta
perl56delta
perl5005delta
perl5004delta
perlartistic
perlgpl
perlcn
perljp
perlko
perltw
perlaix
perlamiga
perlapollo
perlbeos
perlbs2000
perlce
perlcygwin
perldgux
perldos
perlepoc
perlfreebsd
perlhpux
perlhurd
perlirix
perllinux
perlmachten
perlmacos
perlmacosx
perlmint
perlmpeix
perlnetware
perlopenbsd
perlos2
perlos390
perlos400
perlplan9
perlqnx
perlriscos
perlsolaris
perlsymbian
perltru64
perluts
perlvmesa
perlvms
perlvos
perlwin32

MyASPN >> Reference >> ActivePerl 5.10 >> Core Documentation
ActivePerl 5.10 documentation

perlfaq5 - Files and Formats


NAME

perlfaq5 - Files and Formats ($Revision: 10126 $)


DESCRIPTION

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

How do I flush/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 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");   # but is this?
        $printer->autoflush(1);

or IO::Socket (which inherits from IO::Handle):

        use IO::Socket;           # this one is kinda a pipe?
        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; # one time flush
        
=head2 How do I change, delete, or insert a line in a file, or append to the beginning of a file?
X<file, editing>

(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"; # <--- HERE'S THE MAGIC
        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 the lines before the change
                {
                print $out $_;
                last if $. == 4; # line number before change
                }
        my $line = <$in>;
        $line =~ s/\b(perl)\b/Perl/g;
        print $out $line;
        while( <$in> )   # print the rest of the lines
                {
                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<__END__> or C<__DATA__>.
        
        while( <$in> )
                {
                next if /^\s+#/;             # skip comment lines
                last if /^__(END|DATA)__$/;  # stop at end of code marker
                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> }; # slurp!
                # do your magic here
        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

How do I count the number of lines in a file?

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.

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

-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