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


in reply to Re: File existance check failure
in thread File existance check failure

Much Thanks.

With that I brewed the following:

sub fexist($) { my $str = shift; for (glob qq("$str")) { return 1 if -e "$_"; } return 0; }

However I have use for the Link, Directory, File result so:

sub fexist($) { my $str = shift; for (glob qq("$str")) { return 3 if -l "$_"; return 2 if -d "$_"; return 1 if -f "$_"; } return 0; }

Critiques ??
Comments ??
Suggestions ??
Improvements ??

Thanks

-Enjoy
fh : )_~

Replies are listed 'Best First'.
Re^3: File existence check failure
by Athanasius (Archbishop) on Nov 11, 2012 at 04:11 UTC
    Critiques ??

    As a general rule, avoid subroutine prototypes unless you have good reason for them. (See, e.g., Far More than Everything You've Ever Wanted to Know about Prototypes in Perl -- by Tom Christiansen.) With the prototype removed, and employing some Perl idioms, sub fexist can be simplified to:

    sub fexist { for (glob $_[0]) { return 3 if -l; return 2 if -d; return 1 if -f; } return 0; }
    Improvements ??

    Since the aim is to cleanup unwanted files, perhaps it would be better to integrate sub fexist with the cleanup code? Something like this:

    use v5.14; ... sub cleanup { for (glob $_[0]) { cleanup_link($_) when -l; cleanup_dir ($_) when -d; cleanup_file($_) when -f; } }

    Hope that helps,

    Athanasius <°(((><contra mundum

      Thanks,

      Awakens the the spacy name beast!

      Proto's ... geez my Cisims bite again. :)

      -Enjoy
      fh : )_~

Re^3: File existance check failure
by graff (Chancellor) on Nov 12, 2012 at 03:05 UTC
    One more small detail, which probably won't be significant unless you happen to be scanning very large quantities of files, links and/or directories: you can use the special operand "_" (the underscore character) on the file-test operators, in order to use the file stat information from the previous stat call (so you don't do repeated stat calls on the same file). Adapting the most recent suggestion from Athanasius:
    sub cleanup { for (glob $_[0]) { cleanup_link($_) when -l; cleanup_dir ($_) when -d _; cleanup_file($_) when -f _; } }