Tuesday, 4 March 2014

Perl Writing to a file and Reading a file program.

Writing to a file
#!/usr/bin/perl
use strict;
use warnings;
use Path::Class;
use autodie; # die if problem reading or writing a file
my $dir = dir("/tmp"); # /tmp
my $file = $dir->file("file.txt"); # /tmp/file.txt

# Get a file_handle (IO::File object) you can write to
my $file_handle = $file->openw();

my @list = ('a', 'list', 'of', 'lines');

foreach my $line ( @list ) {
    # Add the line to the file
    $file_handle->print($line . "\n");
}
Appending to a file
# As above but use open('>>') instead of openw()
my $file_handle = $file->open('>>');
Reading a file
#!/usr/bin/perl
use strict;
use warnings;

use Path::Class;
use autodie; # die if problem reading or writing a file

my $dir = dir("/tmp"); # /tmp

my $file = $dir->file("file.txt");

# Read in the entire contents of a file
my $content = $file->slurp();

# openr() returns an IO::File object to read from
my $file_handle = $file->openr();

# Read in line at a time
while( my $line = $file_handle->getline() ) {
        print $line;
}
Path::ClassDescription: external link makes working with directories (Path::Class::DirDescription: external link) and files (Path::Class::FileDescription: external link) clean and easy to do. Try to work with file() or dir() objects throughout your code, but remember if you are calling other Perl modules you will often need to convert the object to a string using 'stringify':
    $file->stringify();
    $dir->stringify();


No comments:

Post a Comment