Operating System - Linux
1752273 Members
4769 Online
108786 Solutions
New Discussion юеВ

Re: check to see if multiple files exist

 
Rahul_13
Advisor

check to see if multiple files exist

I have written a perl script in which I need to check if files exist in a directory and then remove them from that directory.

I am doing the following:

my @arr = `ls \directory\file*`;

my $arr_cnt = $#arr +1;

if ($arr_cnt > 0)
{
foreach (@arr)
{
unlink($_);
}
}


This works fine if there are files in the directory but retuns an error message that no file exist in that directory if that directory does not have files of the specified pattern.

I know that I cannot check if multiple files exist with the file test.

Can anyone help.

Thanks,
Rahul
5 REPLIES 5
Marvin Strong
Honored Contributor

Re: check to see if multiple files exist

seems like overkill for perl to me but

if (scalar(@arr) > 1) { do something }

that should tell you if you have multiple items in your array.
A. Clay Stephenson
Acclaimed Contributor

Re: check to see if multiple files exist

You just need to redirect stderr of your ls.

my @arr = `ls \directory\file*`;
becomes:
my @arr = `ls \directory\file* 2>/dev/null`;

If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor

Re: check to see if multiple files exist

Hi Rahul:

#!/usr/bin/perl
my @arr = glob "/path/file*";
unlink for (@arr);

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: check to see if multiple files exist

Hi Rahul:

The 'glob' is a Perl built-in, so it's faster than invoking an external 'ls'.

That aside, there is no need to test for the number of array elements --- the 'foreach' (or shorter 'for') iterates over the array (or list) until there are no more elements. If there are none to begin with, the loop terminates immediately.

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: check to see if multiple files exist

Hi Rahul:

Actually, we can eliminate iterating over the list; pass it in it's entirely to 'unlink'; count the number of files removed; and print that summary in one short piece of code. For example:

# perl -e '$n=unlink glob("/tmp/*.log");printf "%d file%s unlinked\n", $n, $n==1 ? "":"s"'

Regards!

...JRF...