Friday, November 8, 2019
How to Distinguish Between a File and a Directory in Perl
How to Distinguish Between a File and a Directory in Perl          Lets say youre building a Perl script to traverse a file system and record what it finds. As you open file handles, you need to know if youre dealing with an actual file or with a directory, which you treat differently. You want to glob a directory, so you can continue to recursively parse the filesystem. The quickest way to tell files from directories is to use Perls built-in ââ¬â¹File Test Operators.à  Perl has operators you can use to test different aspects of a file. The -f operator is used to identify regular files rather than directories or other types of files.          Using the -f File Test Operator       #!/usr/bin/perl -w$filename  /path/to/your/file.doc;$directoryname  /path/to/your/directory;if (-f $filename) {print This is a file.;}if (-d $directoryname) {print This is a directory.; }         First, you create two strings: one pointing at a file and one pointing at a directory. Next, test the $filename with the -f operator, which checks to see if something is a file. This will print This is a file. If you try the -f operator on the directory, it doesnt print. Then, do the opposite for the $directoryname and confirm that it is, in fact, a directory. Combine this with a directory globà  to sort out which elements are files and which are directories:         #!/usr/bin/perl -wfiles  *;foreach $file (files) {if (-f $file) {print This is a file:  . $file;}if (-d $file) {print This is a directory:  . $file;}}ââ¬â¹         A complete list of Perl File Test Operatorsà  isà  available online.    
Subscribe to:
Post Comments (Atom)
 
 
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.