I have this regex $folder =~ / (?!\d{3}) /xmi
which I use to match inversely match folders that do not follow our 3 number naming convention. It also catches loose files I found out.
My issue is I need it to NOT match the name of specific folder called Junk
which is something like recycle bin for my script. If the script wipes it then there is no point to having it.
How can I make that work?
Also, is that 开发者_运维技巧the correct way to do an inverse match in perl? I found that answer on some website and it works but could it be better?
$folder =~ / (?!\d{3}) /xmi
almost certainly isn't matching what you intend it to match: it will match any point in a string that isn't followed by 3 digits.
This means it will match "no numbers"
or it'll also match "123"
, because it'll match against any of the points that aren't followed by 3 digits: the first digit is followed by only two, etc.
You're better off checking that $folder
doesn't match a regexp that matches 3 digits, either by use of !~
(the opposite of =~
) or using not
or unless
:
if( $folder !~ /\d{3}/ )
{
# Do stuff.
}
That will only check that there aren't 3 digits anywhere in the filename though, if you mean at the start or end of the filename, or for the entire of the filename, you need to anchor your regexp:
/^\d{3}/ # starts with 3 digits
/\d{3}$/ # ends with 3 digits
/^\d{3}$/ # consists entirely of 3 digits
Checking that the filename doesn't match "Junk" is best handled as a separate clause in your if statement rather than trying to make it part of the same regexp:
if( $folder !~ /\d{3}/ and $folder ne 'Junk' )
{
# Do stuff.
}
You can't tell if something is a directory with a regexp, for that you need the -d
operator, so to ignore files you need to check -d $folder
.
if( -d $folder and $folder !~ /\d{3}/ and $folder ne 'Junk' )
{
# Do stuff.
}
Finally the special directories .
and ..
for current and parent directory won't match your 3 digit naming convention either, so you'll want to exclude those too if you aren't already.
Why not just use a regex and a comparison?
$folder =~ / (?!\d{3}) /xmi && $folder ne 'Junk'
As far as an inverse match goes, that works as well as anything. The Perl philosophy is "There is more than one way to do it." You could also do a check to insure that three digits are present, and then invert the result:
print "Bad folder name: $folder"
unless $folder =~ /\d{3}/ or $folder eq 'Junk';
精彩评论