I am working on a project which at one point gets a list of files from an ftp server. At that point it either returns an arrayref of files OR if an optional regex reference (i.e. qr
), is passed it filters the list down using grep. Further if that qr
has a capture group, it treats the captured section as a version number and returns instead a hashref where the keys are the versions and the values are the file names (which would have been returned as the array if no capture groups). The code looks like (simplified slightly)
sub filter_files {
my ($files, $pattern) = @_;
my @files = @$files;
unless ($pattern) {
return \@files;
}
@files = grep { $_ =~ $pattern } @files;
carp "Could not find any matching files" unless @files;
my %versions =
map {
if ($_ =~ $pattern and defined $1) {
( $1 => $_ )
} else {
()
}
}
@files;
if (scalar keys %versions) {
return \%versions;
} else {
return \@files;
}
}
This implementation tries to create the hash and returns it if it succeeds. My question, is can I detect that the qr
has a capture group and only attempt to create the hash if it does?