#!/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:

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.


In reply to Re: directory listing by mr_mischief
in thread directory listing by muizelaar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.