#!/usr/bin/perl
use strict;
use warnings;
my $dir = '/opt/DSPKG';
opendir my $dh, $dir || die "Can't open $dir: $!\n";
open my $out, '>', '/tmp/pkgtest' || die "Can't open pkgtest: $!\n";
foreach ( readdir $dh ) {
print $out $_ . "\n" if -d "$dir/$_" && $_ !~ /^\.{1,2}$/;
}
close $out || die "Error closing pkgtest: $!\n";
Notice the following, which will help you in the long run:
- scalar directory handles and file handles instead of barewords
- three-argument open rather than two-argument open
- die() with a newline -- leave it out if you want the "died at line ##" message, or put it in to get nice, clean custom error messages. This one's a preference, but it's good to know your options.
- There's no particular need to make an array just to hand it to foreach. The foreach loop will take results in list context directly.
- It's good to know you can specify your loop variables, but in some cases using $_ is nice and clear. I'm using that here.
- The negative regex match takes care of '.' and '..'. The -d makes sure you're only getting directories in your output. This saves you the separate loop of the grep.
- Although strictly not necessary in this small of an isolated program, you might like to get accustomed to closing your file handles. The success test on closing helps you deal with things such as out-of-disk-space conditions.
If building the array with grep and handing it to foreach is clearer for you, it's fine to do things that way. I wouldn't want to promote doing away with that simply for the sake of doing so. I, personally, find it clearer when the test is made inside the main loop rather than in a secondary looping construct.
I like doing away with the array as well, as it lets me focus on what's being done to the data rather than where it's being stored.
Scalar filehandles and directory handles are how things tend to be done these days. The language is moving away from barewords for such things, and for scoping reasons it's smart to use scalars. Bareword handles are package-scoped. Scalar ones can be declared lexical with my.
|