in reply to My regex works, but I want to make sure it's not blind luck

G'day SergioQ,

Your approach to learning and fully understanding what you are doing is very good; and in response to that, you're getting good advice.

However, in this particular case, I don't believe a regex is the right tool for the job. It would be far more efficient to use Perl's built-in string handling functions.

$ perl -E ' my @images = qw{a.png b.gif c.svg d.jpg}; for (@images) { say substr $_, rindex $_, "."; } ' .png .gif .svg .jpg

See the documentation for those: substr and rindex.

Note: if you provide some representative, sample data, I may have additional, or even different, advice.

— Ken

Replies are listed 'Best First'.
Re^2: My regex works, but I want to make sure it's not blind luck
by Marshall (Canon) on Dec 29, 2020 at 21:19 UTC
    I guess if we are going to beat this thing to death, split() could also be used:
    use strict; use warnings; my @images = qw{a.png b.gif c.svg d.blah.jpg ..}; foreach (@images) { my $after_last_dot = (split (/\./,$_))[-1]; $after_last_dot //= ''; print ".",$after_last_dot,"\n"; } __END__ .png .gif .svg .jpg . <=might want something else here?
    I believe that the substr, rindex approach will be by far the fastest - these are very simple functions. The regex will be slower, but in my opinion, it is much easier to understand and I would prefer it for that reason. For most of my work, the speed difference would not be of any significance what-so-ever. There are of course always exceptions if you do something enough times! I suppose that split() performance would possibly wind up performance wise somewhere in-between? Although without benchmarking, I can't be sure. It could actually be slower than the first regex method because of more things pushed onto the output array.

    Anyway in the spirit of "more than one way to do it", see split() solution. I did add code to handle the "undefined" case. The //= operator is a cool thing.