![]() | |
![]() |
![]() |
![]() | |
![]() | |
Perl Modules to Manipulate Files | |
![]() |
Modules are not in the standard distribution, are linked to CPAN.
Many modules described further down can be replaced with IO::All, which is full-featured.
use Perl6::Say; say "hello, world";
use Perl6::Say; use IO::All; my $fn= "myfile"; my $contents= "Contents of file\n has two lines"; my $dir= "/home/toma/perl/examples/io/one/two/index.html"; # IO::All way # Old way io($fn) < $contents; # File::Flat->write($fn,$contents); say "yes" if io($fn)->is_file; # File::Flat->exists($fn); say io($fn)->slurp; # File::Flat->slurp($fn); io($fn.'.new') < io($fn); # File::Flat->copy($fn,$fn.'new'); io($dir)->mkpath; # File::Flat->makeDirectory($dir); # File::Slurp my $stuff < io($fn); # $stuff= read_file($fn); my @lines = io($fn)->slurp; # @lines= read_file($fn); io($fn) < join '', @lines; # write_file($fn, @lines); # Compare this to File::List (see below) # Include directories in file search say "Search, include directories"; my @myfiles = io->curdir ->filter(sub {$_->name =~ /(my|one)/}) ->All; # Search for files only say "Search, include only files"; @myfiles = io->curdir ->filter(sub {$_->name =~ /(my|one)/}) ->All_Files; # File::Spec->splitpath($dir.$fn); my ($vol, $dir, $fn)= io($dir.$fn)->splitpath;
use File::Flat; my $fn= "myfile"; my $contents= "Contents of file"; File::Flat->write( $fn, $contents ); File::Flat->exists( $fn ); File::Flat->slurp( $fn ); File::Flat->copy( $fn, $fn_new ); File::Flat->makeDirectory( $dir ); # Can also specify a mode
use File::List; my $dir="/usr/local/index.html"; my $search = new File::List($dir); # Set the base of the find $search->show_empty_dirs(); # show empty directories in output my @files = @{ $search->find("\.pl\$") };# escape $ in string, . in regex my @files = @{ $search->find("my*") }; # usually no escaping is needed
use File::Slurp; my $all_of_it = read_file($filename); my @all_lines = read_file($filename); write_file($filename, @contents) overwrite_file($filename, @new_contnts); append_file($filename, @additional_contents); my @files = read_dir($directory);
use IO::File; my $fn="thisfile"; my $fh = new IO::File; $fh->open($fn) or die "Can't open $fn for read\n"; $fh->close;Writing:
use IO::File; $fh = new IO::File ">$fn" or die "Can't open $fn for write\n"; print $fh "bar\n"; $fh->close;
use File::Spec; my ($volume, $dirname, $fn) = File::Spec->splitpath($full_name);
Example Programs |
#!/usr/bin/perl # # Tom Anderson Copyright (C) 2003 All Rights Reserved # # File::Flat and File::List example program # use strict; use warnings; use diagnostics; use File::Flat; use File::List; my $search = new File::List("/usr/local/man/index.html"); $search->show_only_dirs(); my @dirs = @{ $search->find(".*") }; foreach my $dirname (@dirs) { File::Flat->makeDirectory("/home/toma/perl/examples/fileflat/t3/index.html". $dirname); }