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

Hi, I am trying to get all the unique header files in cwd and push it to an array.Can anyone advise how can I do that?

my $cwd = getcwd(); my %seen; find(sub { push @headers , $_=~ /\*\.h/ if -f $File::Find::name && !$seen{$_} +++; }, $cwd);

Replies are listed 'Best First'.
Re: Putting all the files in an array
by Eliya (Vicar) on Mar 20, 2011 at 00:30 UTC

    As you said "unique header files in cwd" I suppose you mean recursively, starting from the cwd (as filenames are always unique per directory).

    use File::Find; my @headers; my %seen; find(sub { push @headers, $_ if -f && /\.h$/ && !$seen{$_}++; }, ".");

      Hi eliya - if I want to get all the file extensions instead of just .h's,how can I change the above code to achieve that?

        Changing a program is usually done using a text editor, and the process is commonly called "programming".

        You will have to employ both, and some understanding of what actually happens in the program. I suggest you read File::Find and perlop to understand the program you have, and then come back if you have specific questions as to how a particular construct in the program works, or what change you made and why it behaves the way it does.

Re: Putting all the files in an array
by Anonymous Monk on Mar 20, 2011 at 00:00 UTC
    use File::Find::Rule my @headers = File::Find::Rule->file->name('*.h')->in($cwd);
Re: Putting all the files in an array
by wind (Priest) on Mar 20, 2011 at 00:06 UTC
    Just use glob:
    my @headers = glob '*.h'; print "@headers\n";
    Or use File::Spec if you need another directory's files
    use File::Spec; my @headers = glob File::Spec->catfile($dir, '*.h'); print "@headers\n";

    - Miller

    Update: Oh, unique means recursive? Well in that case I would've done the method Eliya suggested, although Anonymous's looks good too.

      I want the "unique" header files