On 4/20/05, Brian Milbrandt <[EMAIL PROTECTED]> wrote: > I am trying to get a script to copy and change the extension for files with > a non-zero file size. I have tried everything I can think of but I can't > seem to get the copy files part right. All I get is the output 0 files > copied. Here is the code if anyone can help. The print function in the > loop is working and displays all the file names. > > Thanks > > #!/bin/perl > # Check to be sure exactly 2 arguments passed to script > die "Must pass exactly 2 arguments to script" if @ARGV != 2; > > # assign meaningfull names to variables > $source = @ARGV[0]; > $target = @ARGV[1]; > > # Check to see if First argument is a directory > # if not exit > die "$source is not a directory \n" if !-d $source; > > mkdir $target, 0755; > > #copy all files with a .abc extension to the target directory > # renaming the extension to xyz > > $filecount = 0; > #foreach my $file (glob "*.abc") > #{ > > opendir SOMEDIR, $source; > while ($file = readdir SOMEDIR) > { printf " the file name is %s\n", $file; > if (-s > 0) > { > printf " non zero file \n"; > foreach my $file (glob "*.abc") > { my $newfile = $file; > $newfile =~ s/\.abc$/.new/; > $newfile = $target."/".$newfile; > rename $file, $newfile; > $filecount += 1; > } > } > } > > # Print the number of files copied > printf "The number of files copied is: %d\n", $filecount; >
Don't reinvent the wheel here; check out File::Rename from cpan. As for what's going on here, if you'd bothered to turn on warnings and strict, you'd be getting errors about use of uninitialized values at this line: if (-s > 0) Since you don't specify anything to test against, perl tries to test against $_. But since you've defined $file as the loop variable for while, $_ isn't defined. Also, -s > 0 is redundant: -s means "file exists and has a nonzero size." if ( -s $file) Should be a step in the right direction. But really, somebody else has done all this work for you already: use File::Rename. HTH, --jay -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>