Perl File Operation

From GM-RKB
(Redirected from Perl-based File Operation)
Jump to navigation Jump to search

A Perl File Operation is a Perl operation that is a file operation.



References


Examples

Reading & Writing Files

Just reading from a file

 open my $io, "<-" or die "NO STDIN: $!" ;
 while (<$io>) { … }
 close $io ;

 open FILE, "<file.txt" or die $!;
 while (FILE)
   print $_ ;
 }

Mixed Read & Write

# Read from one file and write its contents into another file.

 my $infile = 'foo.txt';
 my $outfile = 'bar.txt';

 open IN, "< $infile" or die "Can't open $infile : $!";
 open OUT, "> $outfile" or die "Can't open $outfile : $!";
 print OUT <IN>;
 close IN;
 close OUT;
Subroutine-based

Subroutine to open a file for writing and write into it.

    sub read_file
    {
        my ($f ) = @_;
        open F, "< $f" or die "Can't open $f : $!";
        my @f = <F>;
        close F;
        return wantarray ? @f : \@f;
    }

Subroutine to open a file for writing and write into it.

    sub write_file
    {
        my ($f, @data ) = @_;
        @data = () unless @data;
        open F, "> $f" or die "Can't open $f : $!";
        print F @data;
        close F;
    }
File Open Codes
  # Shorthand Flags:
  Entities	Definition
  < or r	Read Only Access
  > or w	Creates, Writes, and Truncates
  >> or a	Writes, Appends, and Creates
  +< or r+	Reads and Writes
  +> or w+	Reads, Writes, Creates, and Truncates
  +>> or a+	Reads, Writes, Appends, and Creates
File Management

Rename a File

 rename ("/usr/test/file1.txt", "/usr/test/file2.txt" );

Delete a file

 unlink ("/usr/test/file1.txt");

Misc

sysopen() instead of open()

  • The sysopen function is similar to the main open function, except that it uses the system open() function, using the parameters supplied to it as the parameters for the system function. For example, to open a file for updating, emulating the +<filename format from open:
  sysopen(DATA, "file.txt", O_RDWR);

Fcntl module

use Fcntl;              # Import standard fcntl.h constants.
use Fcntl ":flock";     # Import LOCK_* constants.
use Fcntl ":seek";      # Import SEEK_CUR, SEEK_SET, SEEK_END.
use Fcntl ":mode";      # Import S_* stat checking constants.
use Fcntl ":Fcompat";   # Import F* constants.

O_ Flags includes in Fcntl module

  Value	Definition
  O_RDWR	Read and Write
  O_RDONLY	Read Only
  O_WRONLY	Write Only
  O_CREAT	Create the file
  O_APPEND	Append the file
  O_TRUNC	Truncate the file
  O_EXCL	Stops if file already exists
  O_NONBLOCK	Non-Blocking usability

Choose between STDIN or file

my $file = shift @ARGV;

my $ifh;
my $is_stdin = 0;
if (defined $file){
  open $ifh, "<", $file or die $!;
} else {
  $ifh = *STDIN;
  $is_stdin++;
}

while (<$ifh>){
   # Process
}
close $ifh unless $is_stdin;

Directory-based operations

Read a directory's files (shortcut with pattern matching).

 my @list = <"/usr/bin/*e"> ;
 # @list = glob("*e*") ;

Load all files in a directory into the @files array

 # load all files in a director into the @files array
 my $dirToRead = "/usr/bin" ;
 opendir(DIR, $dirToRead) or die "can't open dir $dirToRead: $!" ;
 my @files = readdir(DIR);
 closedir(DIR);
 
 # build a unsorted list from the @files array:
 foreach $file (@files) {
    next if ($file eq "." or $file eq "..");
    print $file ;
 }

another example

 my $dirToRead = "/usr/bin" ;

 opendir(MYDIR, $dirToRead) or die "can't open dir $dirToRead: $!" ;
 #my @dirContents = grep(!/^\.\.?$/, readdir(MYDIR)) ;
 my @dirContents = grep {!/^\.\.?$/ && /p$/} readdir(MYDIR) ;

 print "Files in $dirToRead:\n" ;
 foreach my $file (@dirContents )
 {
	  next if $file =~ /^\.\.?$/ ;  # another way to skip . and ..
	  print "$file \n" if -T "$dirToRead/$file" ; # if the file is a {T}ext file.
 }
 closedir(MYDIR) ;

a subroutine approach

 use DirHandle ;
 sub plainFiles {
	 my $dir = shift;
	 my $dh = DirHandle->new($dir)    or die "can't opendir $dir: $!" ;
	 return sort                      # sort pathnames
	        grep {   -f      }        # chose only "plain" files
	        map  { "$dir/$_" }        # create full paths
	      	grep {  !/^\./   }        # filter out dot files
	      	$dh->read();              # read all entries
 }

JSON-based operations
use JSON; # imports encode_json, decode_json, to_json and from_json.
 
# simple and fast interfaces (expect/generate UTF-8)
$utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
$perl_hash_or_arrayref  = decode_json $utf8_encoded_json_text;

# OO-interface
$json = JSON->new->allow_nonref;
$json_text   = $json->encode( $perl_scalar );
$perl_scalar = $json->decode( $json_text );