UsefulUserName UsefulUserName - 5 months ago 10
Perl Question

Perl using regular expressions to identify file extensions in a list of files

I have a long list of files and I am trying to make decisions based on their extensions. This whole thing has to be part of a perl-program of mine. Here is an example for the list:

a.pj
b.pj
null
c.xlsx
gibberishWithNoExtension
d.pj
f.docx
g.pj 1.17 and 1.15.1.1


The decision rules are:

1) If the extension is ".pj" do something.
2) If the extension is anything else do something else
3) If there is something else after the extension (like version numbers) or there is no extension at all: ignore it


The first point should be fairly easy. I guess it would look like this:

my $string = a.pj;
if ($string =~ /.pj/) {
say 'success!'
}


But I am stuck on the other cases. Especially when it comes to identifying point 3. Could some of you help me to find the right regular expressions?

Answer

It seems easier to check 3 before 2:

#!/usr/bin/perl
use warnings;
use strict;

while (<DATA>) {
    chomp;
    if (/\.pj$/) {
        print "Doing something with $_\n";

    } elsif (/ / || ! /\./) {
        print "Ignoring $_\n";

    } else {
        print "Doing something else with $_\n";
    }
}

__DATA__
a.pj
b.pj
null
c.xlsx
gibberishWithNoExtension
d.pj
f.docx
g.pj 1.17 and 1.15.1.1

Note the backslash in the first regex. Bare dot matches anything but newline, but you don't want to match a.xpj. The dollar sign is needed to prevent matching a.pjx.

Comments