A couple of things I notice...
- If you pass a directory other than the current directory, the script will be unable to find the tar file.
- The code inside your if/elsif is the same, so you can reduce it to a single if test.
- It would be more intuitive to use @list in the foreach loop, instead of using 0..$#list and an index variable. Actually, a while loop might be better, especially if there are many files in the subdirectory. That way you won't have to read the entire list into memory.
- The actual call to tar is insecure. For example, someone might name a file "; rm -rf /; .tar.gz", and if root runs this script over that directory, your filesystem will be hosed. Avoid calling the shell by giving multiple arguments to system.
I might rewrite the code like this:
#!/usr/bin/perl -w
$|++;
use strict;
my $total=0;
my $dir = shift || die "Needs Directory Param!\n";
opendir LOCAL,$dir or die "Can't open directory '$dir': $!\n";
while (my $file = readdir LOCAL)
{
next unless $file =~ /\.t(?:ar\.)?gz\z/;
system("tar", "xzvf", "$dir/$file");
$total++;
}
closedir LOCAL;
print "$total files expanded!\n";
Update: fixed a typo as pointed out by
straywalrus.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.