Sep 13, 2012

Perl File Operations Read, Write

Reading from File:
#########################

 #!/usr/local/bin/perl

 my $filename = '/path/to/your/data.txt';

  unless (-e $filename) {
    print "File Doesn't Exist!";
 }

 open (MYFILE, $filename);
 while (<MYFILE>) {
     chomp;
     print "$_\n";
 }
 close (MYFILE);

Writing to File
######################

 #!/usr/local/bin/perl

 my $filename = '/path/to/your/data.txt';

 if (-e $filename) {
    print "File Exists!";
 }

 unless (-e $filename) {
    print "File Doesn't Exist!";
 }

 open (MYFILE, ">>$filename");
 print MYFILE "Bob\n";
 close (MYFILE);

 use the > single greater than symbol to tell the open function that you want a fresh file each time.
 use the >> to append to the file data.txt


File::Basename for type of file
##################################

#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
use File::Basename;

    #my($filename, $directories, $suffix) = fileparse($path);
    #my($filename, $directories, $suffix) = fileparse($path, @suffixes);
    #my $filename = fileparse($path, @suffixes);
   
    #fileparse("/foo/bar/baz");        - On Unix returns ("baz", "/foo/bar/", "")       
    #fileparse('C:\foo\bar\baz');    - On Windows returns ("baz", 'C:\foo\bar\', "")
    #fileparse("/foo/bar/baz/");    - On Unix returns ("", "/foo/bar/baz/", "")

my @exts = qw(.txt .zip);
   
while (my $file = <DATA>) {
  chomp $file;
  my ($dir, $name, $ext) = fileparse($file, @exts);
   
  given ($ext) {
    when ('.txt') {
      say "$file is a text file";
    }
    when ('.zip') {
      say "$file is a zip file";
    }
    default {
      say "$file is an unknown file type";
    }
  }
}

__DATA__
file.txt
file.zip
file.pl


File::Type (mime_type)
##########################

use strict;
use warnings;
use File::Type;

my $file      = '/path/to/file.ext';
my $ft        = File::Type->new();
my $file_type = $ft->mime_type($file);

if ( $file_type eq 'application/octet-stream' ) {
    # possibly a text file
}
elsif ( $file_type eq 'application/zip' ) {
    # file is a zip archive
}

No comments:

Post a Comment