My linux world » Perl – Files and Folders

Perl - Files and Folders


Contents

Files

Dot someting if file does not exists

unless(-e "myfile.txt"){
  #file does not exists.
  (...)
}

Read file line by line

# open file
open(MYFILE,"<myfile.txt") or die "Fail to open myfile.txt\n";
 
# read each line of the file. Each line is available in $_
while(<MYFILE>) 
{ 
  # avoid \n on last field
  chomp $_;
 
  my $line = $_;
}
 
# close file
close(MYFILE);

Open file using encoding UTF-8

open(FILE, '<:encoding(UTF-8)', "myFile.txt") || die "Can't open myFile.txt: $!";

Load lines file in array

open(FILE, "myFile.txt") || die "Can't open myFile.txt: $!";
my @allLines=<FILE>;
close(FILE);

Write file

# open file
open(MYFILE,">myfile.txt") or die "Fail to open myfile.txt\n";
 
# print line to file:
print MYFILE "HelloWorld";
 
# close file
close(MYFILE);

Folders

Get current folder

use Cwd;
 
my $currentFolder = getcwd;

Read folder

opendir(DIR, "/my/directory") || die "Can't open /my/directory: $!";
 
while (readdir DIR) {
 
   if(-f "/my/directory/$_") {
     print "[FILE]\t";
   }
   elsif(-d "/my/directory/$_") {
     print "[FOLDER]\t";
   }
   else {
     print "[UNKNOWN]\t";
   }
 
   print "/my/directory/$_\n";
}
 
closedir DIR;

To read only all folders :

opendir(DIR, /my/directory) || die "Can't open /my/directory: $!";
my @folders= grep { /^[^\.]+$/ && -d "/my/directory/$_" } readdir(DIR);  
closedir DIR;
 
foreach my $folder (@folders) {
   print "folder: $folder\n";
}

Create folder recusivly

# install module File::Path
yum -y install perl-File-Path
# import module :
use File::Path;
 
# use it :
File::Path::mkpath("my/recurse/folder");

Remove folder recusivly

# install module File::Path
yum -y install perl-File-Path
# import module :
use File::Path;
 
# use it :
File::Path::rmtree("my/recurse/folder",0,0);

Redirect STDOUT / STDERR

# redirect stdout to log file :
open(STDOUT, ">/var/log/perl.log" );
 
# redirect stderr to stdout :
open(STDERR, ">&STDOUT" );

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.