Perl Archive::Tar -
i want archive txt files file::find, delete source files , remove empty directories.
i'm having difficulties renaming files '$tar->rename( );' because i'd to strip them full path names , use parent directory/*.txt, whatever try code renames 1 file.
don't know appropriate place execute 'unlink' function.
thanks.
use strict; use warnings; use archive::tar; use file::find; use file::basename; $dir = "e:/"; @files = (); find(\&archive, $dir); sub archive { /\.txt$/ or return; $fd = $file::find::dir; $fn = $file::find::name; $folder = basename($fd); $file = $_; push @files, $fn; $tar = archive::tar->new(); $tar->add_files(@files); $tar->rename( $fn, $folder."\\".$file ); $tar->write($fd.'.tar'); unlink $fn; finddepth(sub{rmdir},'.'); }
you using file::find interface incorrectly. archive sub gets called once on every file found. end creating new tar on every call, adding single file , writing out.
correction: end trying add found files, you've unlinked except last one.
let's in small steps - first find , classify .txt files according directory, add them relevant tar files, , clean up:
my $dir = "e:/"; %txt_files = (); find(\&classify, $dir); sub classify{ /\.txt$/ or return; $fd = $file::find::dir; $fn = $file::find::name; push @{$txt_files{$fd}||=[]}, $fn; } foreach $folder (keys %txt_dirs) { @files = @{$txt_files{$folder}}; $foldername = basename($folder); $tar = archive::tar->new(); $tar->add_files(@files); $tar->rename( $_, $foldername."/".basename($_)) @files; $tar->write($folder.'.tar'); } # remove txt files we've found unlink map {@{$_}} values %txt_files; # try remove directories contained txt files eval {rmdir} keys %txt_files;
Comments
Post a Comment