Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Perl (http://www.go4expert.com/articles/perl-tutorials/)
-   -   File Tips & Trick in Perl (http://www.go4expert.com/articles/file-tips-trick-perl-t9665/)

pradeep 31Mar2008 17:24

File Tips & Trick in Perl
 
Here are a few tips & tricks which you may find useful when dealing with files/directories in Perl.

Perl Test Operators



Code:

+-------------+------------------------------------+
 | Operator    | Function                          |
 +-------------+------------------------------------+
 |-e          | Tests if OPERAND exists.          |
 +-------------+------------------------------------+
 |-f          | Tests if OPERAND is a regular file |
 |            | as opposed to a directory,        |
 |            | symbolic link or other type of file|
 +-------------+------------------------------------+
 |-l          | Tests if OPERAND is a symbolic link|
 +-------------+------------------------------------+
 |-s          | Returns size of OPERAND in bytes  |
 +-------------+------------------------------------+
 |-d          | Tests if OPERAND is a directory.  |
 +-------------+------------------------------------+
 |-T          | Tests if OPERAND is a text file.  |
 +-------------+------------------------------------+

Example:
Code: Perl

#!/usr/bin/perl
 
 if(-e "/tmp/test.pl")
 {
     print "File/directory exists.";
 }
 
 if(-f "/tmp/test.pl")
 {
     print "File exists";
 }
 
 $size = -s "/tmp/test.pl";
 print "Size of /tmp/test.pl is $size bytes";


Filtering Files With Some Characteristics



We can use a combination of grep and perl test operators to filter some files out, to match some criteria of ours, like getting only text files.

Code: Perl

#!/usr/bin/perl
 
 $path = "/tmp/test/";
 opendir(DIR, $path);
 
 @arr1 = readdir DIR;
 @arr2 = grep{-T "$path$_"} @arr1; #only text files only
 @arr3 = grep{!-d "$path$_"} @arr1; #no directories
 @arr4 = grep{-s "$path$_" < 2048} @arr1; #less than 2KB
 @arr5 = grep{/^a/} @arr1; #filenames starting with 'a'

Finding the basename of a file from its full path-name



Code: Perl

#!/usr/bin/perl
 
 use File::Basename;
 
 $path = "/home/htdocs/go4expert.com/cgi-bin/index.cgi";
 $basename = basename($path, ".cgi");
 
 print $basename;

Output:
Code:

index
To find just the name of the file, without its preceding path, and minus the "dot extension" using File::Basename module is pretty easy. We just pass it the whole path, and a string that specifies what extension we want removed and presto we're done.


All times are GMT +5.5. The time now is 17:31.