excluding directories in file tests for perl

user380892 Source

I am taking arguments from the command line to test if they exist print out their names if they do. In this code directories are printed out if they exist. How do I exclude directories?

#!/usr/bin/perl
use strict;
use warnings;


foreach my $x (@ARGV) {
  if (-e $x){
    print "$x ";
  else {
    print "'$x' does not exist"
  }
}
exit;
perl

Answers

answered 6 months ago xxfelixxx #1

Use the file test operator -d to test if you have a directory.

In your code, you can skip directories by adding:

next if -d $x;

See perldoc -f -X for details on this and all other file test functions.

comments powered by Disqus