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

I am using a config file to reference directories that are searched for files that are older than the number of days also listed in the config file. If any meet the criteria, they are gzip'd. I am attempting to use opendir to view the current directory being searched, followed by grep on the pattern specified in the config file identified as $pattern in my script. I'm kinda stuck on this and could use some suggestions or ideas. Thanks.
opendir(TARGET, ".") or die "Can't open current directory: $!"; my @targets= grep $pattern readdir TARGET; my $gzip_count = 0; foreach my $target (@targets) { my $cnt = 0; if (-M $target > $expiration) { $gzip_count++; $cnt = `gzip $target`; } }
Thanks si_lence, Your suggestion worked, and now I can move on. Appreciate the immediate response.

Replies are listed 'Best First'.
Re: Opendir and regex
by Zaxo (Archbishop) on Nov 16, 2004 at 18:37 UTC

    You could instead call glob, which combines directory search and pattern matching on file names. With that you can write,

    for (glob '*.{log,txt}') { -M > $expiration and system '/usr/bin/gzip', $_; }
    Yet another way is with File::Find. That would be the choice if you wanted to process subdirectories, too.

    After Compline,
    Zaxo

Re: Opendir and regex
by si_lence (Deacon) on Nov 16, 2004 at 17:57 UTC
    I think the problem is that your pattern is not recognized as one
    If you take the match out of your $pattern variable and put it directly
    in your grep it should work
    opendir(TARGET, ".") or die "Can't open current directory: $!"; my $pattern = '\.pl$'; my @targets= grep {m/$pattern/} readdir TARGET; print join ("\n", @targets);

    And then again, I could be wrong ;-)
    si_lence
Re: Opendir and regex
by steves (Curate) on Nov 16, 2004 at 18:17 UTC

    Either of these work in a directory where I have some *.pm files and a bunch of others:

    use strict; my $pattern = '\.pm$'; opendir(TARGET, ".") or die "Can't open current directory: $!"; # First try my @targets = grep(/$pattern/, readdir TARGET); print join("\n", @targets), "\n\n"; # Second try rewinddir(TARGET); @targets = grep {/$pattern/} readdir TARGET; print join("\n", @targets), "\n\n";

Re: Opendir and regex
by gman (Friar) on Nov 16, 2004 at 17:57 UTC
    hommer,
    You did not specify what the problem (error) was?
    Is there anything in your array, are you matching on
    anything? gman
    opendir RDIR, $path; my @DIRLIST = grep { ( /search pattern/ ) && !/\.gz$/ } readdir RDIR;