tags:

views:

71

answers:

3

For ex :

#!/usr/bin/perl
my @arr = ('/usr/test/test.*.con');
my $result = FileExists(\@arr);

print $result ;

sub FileExists {
    my $param = shift;
    foreach my $file (@{$param}) {
        print $file ;
        if (-e $file) {
            return 1;
        }
    }
    return 0;
}

It returns 0. But I want to find all wild characters too... How to solve this ?

+2  A: 

You need to use glob() to get the file list.

Also, I'm not sure why you are passing the array as a reference, when subs take an array by default. You could much more easily write it like this:

my @arr = (...);
my $result = FileExists(@arr);

sub FileExists {
    foreach my $file (@_) {
        ...
    }
    return 0;
}
siride
+4  A: 

-e can't handle file globs. Change this line

my @arr = ('/usr/test/test.*.con');

to

my @arr = glob('/usr/test/test.*.con');

To expand the glob pattern first and then check the matched files for existance. However, since glob will only return existing files matching the pattern, all the files will exist anyways.

jkramer
Perhaps what they'll want to do then is just check to see if glob produces any results at all, i.e.: my @arr = glob(...); print "Yes" if @arr > 0;
siride
Because glob implements shell expansion rules it can in some cases return files that don't exist. For example `glob('no{file,where}')` returns two items and neither exist on my file system.
Ven'Tatsu
+2  A: 

If you want to handle glob patterns, use the glob operator to expand them. Then test all the paths, store the results in a hash, and return the hash.

sub FileExists {
    my @param = map glob($_) => @{ shift @_ };

    my %exists;
    foreach my $file (@param) {
      print $file, "\n";
      $exists{$file} = -e $file;
    }

    wantarray ? %exists : \%exists;
}

Then say you use it as in

use Data::Dumper;

my @arr = ('/tmp/test/test.*.con', '/usr/bin/a.txt');
my $result = FileExists(\@arr);

$Data::Dumper::Indent = $Data::Dumper::Terse = 1;
print Dumper $result;

Sample run:

$ ls /tmp/test
test.1.con  test.2.con  test.3.con

$ ./prog.pl 
/tmp/test/test.1.con
/tmp/test/test.2.con
/tmp/test/test.3.con
/usr/bin/a.txt
{
  '/tmp/test/test.3.con' => 1,
  '/tmp/test/test.1.con' => 1,
  '/usr/bin/a.txt' => undef,
  '/tmp/test/test.2.con' => 1
}
Greg Bacon