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

Hello All!

I am confused. I found a possible solution to finding / deleting zero byte files. Here is the excerpt from the post I would like to discuss is:

If you need to do it from a Perl program, I would do:

# Remove all empty files in '$dir' and below. </p> my $dir = "/some/path"; system "find '$dir' -size 0c | xargs rm";

To write a perl script to make this work, it would look like:

!#/bin/perl # To remove all 0 byte file in a folder my $dir = "/home/bob/mytemp"; system "find '$dir' -size 0c | xargs rm";

This does not work. I can type this from command line:

find . -type f -size 0 | xargs rm

and it deletes all zero byte file.

I can type from cmd line:

find /home/bob/mytemp -type f -size 0 -exec rm {} \;

and it removes all 0 byte file.

BUT,,, when I put it in a perl script, it errors or just does not work.

Can anyone explain why?

Thanks so much

Replies are listed 'Best First'.
Re: Error in script
by Perlbotics (Archbishop) on Aug 15, 2011 at 15:30 UTC

    If you're already going to write a Perl script, why shelling out? Do it all in Perl - or does speed matter that much?

    use strict; use warnings; use File::Find; my @start_dirs = qw(/home/bob/mytemp); sub rm_empty_file { my $file = $File::Find::name; if ( -f $file and -z $file ) { print "removing empty file: $file\n"; #TODO: unlink $file or die "cannot remove $file - $!"; } } find( { wanted => \&rm_empty_file, no_chdir => 1 }, @start_dirs );

Re: Error in script
by toolic (Bishop) on Aug 15, 2011 at 15:15 UTC
    when I put it in a perl script, it errors or just does not work.
    Show your Perl code and show the exact error messages you get, using "code" tags (see Writeup Formatting Tips).
    Here is the excerpt from the post I would like to discuss is
    I believe the post is: UNIX command - remove 0 byte file
Re: Error in script
by GotToBTru (Prior) on Aug 15, 2011 at 16:21 UTC

    Use -s test:

    #!/bin/perl # To remove all 0 byte file in a folder my $dir = "/home/bob/mytemp"; while (<$dir/*>) {unlink $_ unless (-s)}

    Update: first line fixed. When testing I had #!/home/edi/perl but I know our installation is unusual, so I just copied the line from the OP to match his environment .. I thought it looked strange!

    I leave the parentheses around conditions deliberately. It helps the less perl-literate of my co-workers.

    My solution will only delete files in $dir; in the OP it mentions directory and below. find .. -exec rm is the tool to use in that case.

      Nice.

      Though fix your first line. #! makes us all happy. :)

      (And I don't bother with parens around the -s, but both work fine...)

Re: Error in script
by hbm (Hermit) on Aug 15, 2011 at 15:12 UTC
    Try removing the single quotes from '$dir'.