http://www.perlmonks.org?node_id=986579

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

Hello !

I'm trying to write a perl script that search for rar files(and eventually,unrar them into a folder) in a directory that has subdirs.

For example,let's say that i have dir "archive" and this dir contains "cd1","cd2" etc.

Script will get as argument "archive" and will search into it for rar files.Of course,it will open "cd1","cd2" dirs and unrar the content into another folder.

By now,i have a script that search for rar files and unrar only from a dir.But i don't know how to make it to search in every folder.

opendir(DIR, $show_dir); #Opens The Directory my @tempfiles = grep(/\.rar$/,readdir(DIR)); #Scans for files +ending in .rar closedir(DIR); #Closes The Directory my $rar_file = $tempfiles[0]; #Chooses First .rar File Found $rar_file = "$show_dir\/$rar_file"; #Adds Full Path To Rar Fil +e Name my $rar_command = "unrar e \"$rar_file\" \"$output_rar\""; #Cr +eates The Command Used To Unrar print "[INFO] Unraring file, Please Wait.\n"; #Alerts The User + That We Are Going To Unrar `$rar_command`; #Unrars The File

Can someone help me with this?

Many thanks in advance

Replies are listed 'Best First'.
Re: unrar from multiple directories
by 2teez (Vicar) on Aug 09, 2012 at 19:23 UTC
    Hi

    But i don't know how to make it to search in every folder.
    One of the ways of doing that, is using either a recursive subroutine, or use File::Find module.
    Using a recursive subroutine:
    For Example: To list out all the files in different folders in a directory like so:

    use warnings; use strict; scan_dir( $ARGV[0] ); ## call subroutine sub scan_dir { my ($dir) = @_; if ( -d $dir ) { ## check if directory opendir my $dh, $dir or die "can't open directory: $!"; while ( readdir $dh ) { next if $_ eq '.' or $_ eq '..'; print $_, $/; scan_dir("$dir/$_"); ## recursive call } } }
    This can even get simplier using a File::Find module like so:
    use warnings; use strict; use File::Find qw(find); find(\&scan_dir,$ARGV[0]); sub scan_dir{ return if $_ eq '.' or $_ eq '..'; print $_,$/; }
    NOTE:Please, that the codes above is to show how you can transverse a dircetory. To get your rar files, and "unrar", is left for you to figure out. Am sure you will get around it! :)
    Check perldoc File::Find for more info.
    Cheers.

      Thank you very much.

        I will stay all night to find a way to handle with .rar files.