Sonntag, 17. März 2013

Perl IO with IO::All

Working with Files and Directories in Perl Programming is not really a big deal. But there is a  module that ease this in a cool way.

If you want to do IO operations in Perl i advice you to take a look at IO::All.

File Operations


Opening a file in the traditional way is done with the open() function and than you can iterate over the lines.
my @lines;
open my $fh, "<", "the-file";
@lines = <$fh>; 
close $fh;
With IO::All you can simplify this to one line
my @lines = io("the-file")->getlines;
If you want to load a complete file into a string you have to do the following without IO::All:
my $content;
open my $fh, "<", "the-file";
{
    local $/;
    $content = <$fh>; 
} 
close $fh;
Compared to IO::All it looks a bit too much:
my $content = io("the-file")->all;
You can also use the "<" operator (you might already know from bash) to read a file.
my $content < io("the-file");
Writing to a file is also really easy and straight forward compared to the standard way.
open my $fh, ">", "the-file";
print $fh "Hello World\n"; 
close $fh;
With IO::All it is - as you may expect - only one line.
"Hello World\n" > io("the-file");
If you want to append to a file you can just use the ">>" operator.
"Hello World\n" >> io("the-file");

Special File Operations

With IO::All it is also easy to manipulate files without much code.

For example if you want to edit a special line inside a file you can do this with the following code:
my $file = io("the-file");
$file->[10] = "New content in Line eleven";
print $file->[20];

Directory Operations

 If you want to read the contents of a directory in the past you had code like this:
my @contents; 
opendir my $dh, "/dir";
while(my $entry = readdir($dh)) {    
    next if($entry eq "." || $entry eq "..");
    push @contents, $entry;
} 
closedir $dh;
With IO::All you can reduce this to a one liner:
my @contents = io("/dir")->all;
With this function it is also easy to traverse subdirectories.
my @contents = io("/dir")->all(0);
Or, if you don't want to go through every subdirectory you can specify the depth.
my @contents = io("/dir")->all(2);

Keine Kommentare:

Kommentar veröffentlichen