in reply to Re: Zipping Files Help!
in thread Zipping Files Help!

I tried removing the open() and close() outside of the foreach loop, but cause of the zip gets done before the text file the log.txt file inside of the zip file is empty, any suggestions? Thanks!
#!/usr/bin/perl -w # use strict; use CGI qw(:standard); use File::Basename; use File::stat; use File::Slurp qw(read_dir); use Archive::Zip qw( :ERROR_CODES :CONSTANTS ); # zip stuff::: my $zip = Archive::Zip->new(); # new instance #Archive::Zip::setChunkSize( 2000 ); #my $chunkSize = Archive::Zip::chunkSize(); my ($file_path, $file_name, $zipped, $flag,$k_size); $flag = ''; # vars my @files; # get the files from here::: my @directories = qw( /var/www/test_1 /var/www/test_2); # set sizes::: my $min_size = 1024; # bytes => 1K my $max_size = 10485760; # bytes =>10MB # go in the directories::: my $c; for my $d (@directories) { $c++; push @files, grep { -f && -s _ >= $min_size && -s _ <= $max_size } + read_dir( $d, prefix => 1 ); } #get file sizes just in case::: open (INDEXFILE, '>>log.txt'); foreach my $files(@files) { my $size = stat($files)->size / 1024; # size in kilobytes $k_size = sprintf ("%03d", $size); # do some clean up::: $files=~s/[\r\n]+//; if($files =~/(.*?)\/([^\/]+)$/) { $file_path=$1; $file_name=$2; } # creating log file::: print INDEXFILE "$file_name - $k_size Kb\n"; $zipped = $zip->addFile('log.txt') unless $zip->memberNamed('log.txt +'); $zipped = $zip->addFile($files,$file_name); } die $flag="Failed" unless $zip->writeToFileNamed( 'test.zip' ) == AZ_ +OK; close (INDEXFILE); # show status::: if($flag eq "Failed") { print "\n\nError in archive creation!\n\n"; } else { print "\n\nArchive created successfully!\n\n"; }

Replies are listed 'Best First'.
Re^3: Zipping Files Help!
by Lotus1 (Vicar) on Aug 31, 2011 at 22:18 UTC

    This version is trying to add a copy of 'log.txt' to the zip file each time the foreach loop iterates unless the file is already there. That means it adds it the first time and never again.

    It seems like you would want to just print to log.txt inside the foreach loop. Then after the foreach loop, close 'log.txt' and then call $zip->addFile('log.txt') then call writeToFileNamed.

    What is the purpose of the variable $zipped? You don't use it anywhere.

    # do some clean up::: $files=~s/[\r\n]+//;

    Is this intended to remove newlines? Why not use chomp?

    What does the output from this program look like? Is it creating test.zip at all? Does it contain files?

    I suggest you get rid of the 'show status' section at the end. If the program dies that won't run. And there is no use having the variable $flag.