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

Hi, Monks, I am trying to remove .tmp files with more than 7 days age under D:\Log\tmp. But it did not work. It could not get value for $result. Would someone tell me why? Thanks a lot.
#!/usr/bin/perl if(opendir LOGS, "D:\\Log\\tmp"){ my @myfile = grep( /^*.tmp$/, readdir (LOGS)); foreach $file(@myfile){ my $result=-M $file; if( $result> 7){ unlink ($file); } } } closedir LOGS;

Replies are listed 'Best First'.
Re: Why -M doesn't work?
by Tanktalus (Canon) on Feb 07, 2008 at 23:06 UTC

    And this is why I almost always use glob instead of opendir. It's rare that I want filenames without the context of the directory, which is what opendir does. Generally, I want the full relative or absolute name, as glob gives me. Also, the "wildcards" that glob uses make more sense to me in that context (your regexp isn't working anyway).

    my @myfile = glob ('d:/Log/tmp/*.tmp'); foreach my $file (@myfile){ #... }
      Thanks a lot for your information. I did not know glob before. ^ _ ^
Re: Why -M doesn't work?
by runrig (Abbot) on Feb 07, 2008 at 23:01 UTC
    You need to tell unlink what directory you are removing the files from (or chdir to that directory first).
      Thanks a lot.
Re: Why -M doesn't work?
by jrsimmon (Hermit) on Feb 07, 2008 at 23:02 UTC
    You're reading file names from a directory and storing them in an array. If you want to operate on those file names, you need to include your file path with the file name in the operation.
    #!/usr/bin/perl my $dir = "D:\\Log\\tmp"; if(opendir LOGS, "$dir"){ my @myfile = grep( /^*.tmp$/, readdir (LOGS)); foreach $file(@myfile){ my $result=-M "$dir\\$file"; if( $result> 7){ unlink ("$dir\\$file"); } } } closedir LOGS;
Re: Why -M doesn't work?
by GrandFather (Saint) on Feb 07, 2008 at 23:11 UTC

    Always use strictures (use strict; use warnings). In this case you would have been told that /^*.tmp$/:

    ^* matches null string many times in regex; marked by <-- HERE in m/^* <-- HERE .tmp$/ at ...

    ^ anchors the start of the string and it is meaningless to follow it by * which matches the previous match 0 or more times. Actually you should probably omit the anchor and the (implied) 'skip junk' match in any case. Just use /\.tmp$/.


    Perl is environmentally friendly - it saves trees
      ok, I will remember
Re: Why -M doesn't work?
by Joost (Canon) on Feb 08, 2008 at 00:15 UTC
Re: Why -M doesn't work?
by poolpi (Hermit) on Feb 08, 2008 at 08:01 UTC

    CPAN can help you

    #!/usr/bin/perl use strict; use warnings; use File::Find; my @dirs = ('/dir/subdir'); find( \&wanted, @dirs ); sub wanted { my ( $dev, $ino, $mode, $nlink, $uid, $gid ); /^\.tmp\z/s && ( ( $dev, $ino, $mode, $nlink, $uid, $gid ) = lstat($_) ) && ( int( -M _ ) > 7 ) && unlink($_); }
    'Ebry haffa hoe hab im tik a bush'. Jamaican proverb
      Thanks a lot.