Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

selcting all files in a given directory except......

by asdfghjkl (Initiate)
on Dec 06, 2007 at 09:01 UTC ( [id://655317]=perlquestion: print w/replies, xml ) Need Help??

asdfghjkl has asked for the wisdom of the Perl Monks concerning the following question:

hi all, i wanted to list or print all the names of files in a given directory except for '.' and '..' ones. i had come up with a code but having errors .can any one help me out!!
!/usr/bin/perl use strict; use warnings; chomp(my $dir = <STDIN>); if (-d $dir){ opendir ($DIR, $dir); @files = grep {/^(?!\.{1,2}\z)/} readdir($DIR)); closedir($DIR); } foreach $file (@files) { print "$file\n"; }

Replies are listed 'Best First'.
Re: selcting all files in a given directory except......
by moritz (Cardinal) on Dec 06, 2007 at 09:07 UTC
    When you use strict (which is recommended), you have to declare your variables with my:

    After the readdir there is a stray closing parenthesis.

    #!/usr/bin/perl use strict; use warnings; chomp(my $dir = <STDIN>); my @files; if (-d $dir){ opendir (my $DIR, $dir); @files = grep { m/^(?!\.{1,2}\z)/ } readdir($DIR); closedir($DIR); } foreach my $file (@files) { print "$file\n"; }
      names of the files are not been displayed .......
        The script works fine for me.

        Remember to enter a directory name and hit the Return key. And of course the name you type in has to be a valid directory.

        A reply falls below the community's threshold of quality. You may see it by logging in.
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: selcting all files in a given directory except......
by cdarke (Prior) on Dec 06, 2007 at 09:10 UTC
    It would help if you said what the error messages are. Error messages are your friends!

    Your first problem is a missing '#' on the first line. That might be a slip when pasting your code, otherwise it might be trying to execute it as a Bourne shell script.
    Thereafter, you will get strictness errors because you are not pre-declaring all your variables. Try this:
    #!/usr/bin/perl use strict; use warnings; chomp(my $dir = <STDIN>); my @files; if (-d $dir){ opendir (my $DIR, $dir); readdir ($DIR); # ignore . readdir ($DIR); # ignore .. @files = readdir($DIR); closedir($DIR); } foreach my $file (@files) { print "$file\n"; }
      at least for me, the opendir don't return as the first 2 values the '.' and '..'.
      readdir ($DIR); # ignore . readdir ($DIR); # ignore ..
      the solution of moritz it's more robust
      @files = grep {/^(?!\.{1,2}\z)/} readdir($DIR);

        If you want more robust, don't use a regexp to match parent and current directories.

        @files = grep {$_ ne '.' and $_ ne '..'} readdir($D);

        I know one isn't meant to write code that is easy for a monkey to understand, but all the same, I don't think the added complexity of throwing in a couple of more-rarely used regops like \z and (?!...) is worth it in this case.

        This way there is no ambiguity with strange directories like "foo\n.". Also, your original solution may fail if a corrupted filesystem is rebuilt, and the parent and current directories pointers are rewritten elsewhere than positions 1 and 2 in the directory list.

        If you want to go really cross-platform robust, use File::Spec's curdir() and updir() routines.

        • another intruder with the mooring in the heart of the Perl

        Not all directories have . and .. in them, at least in Windows.
      names of the files are not been printed on the terminal when script is excecuted
        try this script ...
        #!/usr/bin/perl use strict; use warnings; my $dir = $ARGV[0] || $ENV{HOME}; my @files; if (-d $dir){ opendir (my $DIR, $dir); @files = grep {/^(?!\.{1,2}\z)/} readdir($DIR); closedir($DIR); } else { die("can't open the dir, $dir\n"); } foreach my $file (@files) { print "$file\n"; }
        save the script as myls.pl, and run the script like this
        $ perl myls.pl /home
        ps. the $ENV{HOME} exist in the windows environment??
        A reply falls below the community's threshold of quality. You may see it by logging in.
        When you ran the preceding example,
        • What input did you give it?
        • What was the expected output?
        • What platform/perl are you running?
        -- Ian Tegebo

        Did you enter dir name and press Enter key?

        A reply falls below the community's threshold of quality. You may see it by logging in.
        Maybe the opendir is failing. Modify that line to read:
        opendir (my $DIR, $dir) || die "Unable to open $dir: $!";

        then try again.
Re: selcting all files in a given directory except......
by Dawesy (Initiate) on Dec 06, 2007 at 10:11 UTC
    I believe the GLOB function will return all files in a given directory, as this is what I use on UNIX / Solaris. Eg: @<list> = glob(<path & wildcard for files>); @ftest = glob(/dir1/file*.sh);
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: selcting all files in a given directory except......
by poolpi (Hermit) on Dec 06, 2007 at 14:27 UTC
    Beginning with Perl v5.6.0, you can use the standard File::Glob extension : see http://perldoc.perl.org/File/Glob.html
    use File::Glob ':globally';</br> my $dir = '/my/dir'; my @files = <$dir/*>; print "$_\n" for @files;
    Hope This Helps
Re: selcting all files in a given directory except......
by kyle (Abbot) on Dec 06, 2007 at 15:55 UTC

    Instead of trying to match everything except those two names, match those two names and negate the test. Also, be sure to check for and report errors.

    opendir my $dh, $dir or die "Can't opendir '$dir': $!"; my @files = grep { ! m{ \A \. \.? \z }xms } readdir $dh; closedir $dh or die "Can't closedir? $!";
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://655317]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2024-04-18 07:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found