index
is not a good idea here, you might get very unexpected behaviour if the extension itself is found somewhere in the middle of filename.
Also: ALWAYS use strict
and use warnings
Regex matching at the end of the string will be a better solution here, see the code below.
$
is a metacharacter used to match the end of the line (or before newline at the end)
#!/usr/bin/perl
use strict;
use warnings;
my $file = "filename.zip";
my @allowedExts = ( '.zip', '.tar.gz', '.tar.bz2' );
my $found = 0;
foreach my $ext (@allowedExts) {
if ($file =~ /\Q$ext\E$/) {
$found = 1;
last;
}
}
print "found" if ($found);
You will probably get loads of other ideas for solving this. As always with perl: TIMTOWTDI.
EDIT:
As @ikegami suggested, regex should be escaped so that the dot is not treated as metacharacter but literal match, \Q
and \E
escape metacharacters in the regex.