[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] Something like "grepfirst"



What is the shortest code for finding the first
existing directory in a path of directories?
Some variants ...
(Variant 4 would work if "-d" returned the directory.)

Can variant 1 be shortened without loosing the feature
that processing is stopped after the first successful test?

Roland



=pod

# Finding first element which passes a test
# VARIANT 1:
use strict;
my $default = $ENV{TEMP};
#------------------
my $dir;
for ('dir1', 'dir2', $default) {$dir = $_; last if -d};
$dir or die;
#------------------
print $dir;

=cut

=pod

# VARIANT 2:
# Shorter but does not stop after first successful test
use strict;
my $default = $ENV{TEMP};
#------------------
my $dir = (grep -d $_, ('dir1', 'dir2', $default))[0] or die;
#------------------
print $dir;

=cut

#=pod

# VARIANT 3:
# Not so short ...
use strict;
my $default = $ENV{TEMP};
#------------------
my $dir = (-d 'dir1' and 'dir1')     ||
          (-d 'dir3' and 'dir3')     ||
       (-d $default and $default) ||
    die;
#------------------
print $dir;

#=cut

=pod

# VARIANT 4:
# Shorter but does not work.
# "-d" returns "1" on succes but not the filename.
#
use strict;
my $default = $ENV{TEMP};
#------------------
my $dir = (-d 'dir1') || (-d 'dir2') || (-d $default) || die;
#------------------
print $dir;

=cut





--
roland.bauer@fff.at
http://www.fff.at/fff/roland/



==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe