On 3/16/07, Rodrigo Faria Tavares <[EMAIL PROTECTED]> wrote:
snip
After I open the file, i like to get a simple word and
store in a scalar variable. Or write after line 10 for
example. And others.
snip

In Perl file operations are generally handled by file handles.  If you
want to use the object oriented interface (and I would recommend that
you do) you should read about the base class IO::Handle* which
contains all of the methods used by handle like objects (sockets,
files, etc) and IO::File** which contains all of the file specific
methods.  What follows is a simple Perl script that writes some lines
to a file name foo.txt, reads them back in, and then appends some data
after the 10th line.

* http://search.cpan.org/~gbarr/IO-1.2301/IO/Handle.pm
** http://search.cpan.org/~gbarr/IO-1.2301/IO/File.pm

#!/usr/bin/perl

use strict;
use warnings;
use IO::File;

my $file = IO::File->new;

#open foo.txt for writing
$file->open('foo.txt', 'w')
       or die "could not open file:$!";

#write some lines to the file
$file->print("this is the line that is first\n");
for my $i (2 .. 12) {
       $file->print("This is line $i\n");
}

#close the file
$file->close;

#open foo.txt for reading
$file->open('foo.txt', 'r')
       or die "could not open file:$!";

#loop over every line in the file
while (defined (my $line = <$file>)) {
       if ($line =~ /line (.*)/) {
               print "I saw line $1\n";
       }
}

#close the file
$file->close;

#open the file for reading and writing
$file->open('foo.txt', 'r+')
       or die "could not open file:$!";

while (defined (my $line = <$file>)) {
       last if $file->input_line_number == 10;
}

$file->print("This is line 11, but it has been replaced\n");

#close the file
$file->close;

#open foo.txt for reading
$file->open('foo.txt', 'r')
       or die "could not open file:$!";

#loop over every line in the file
while (defined (my $line = <$file>)) {
       if ($line =~ /line (.*)/) {
               print "I saw line $1\n";
       }
}

#close the file
$file->close;

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to