Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I get data in an array and want to get the last value of a reg expression match. Is this the best way to do it?
for(@files) { $match = (@_) = $_ =~ /(.{8}\-.{3}\-i32)/g; @stats = pop(@_); print "@stats\n"; }

Replies are listed 'Best First'.
Re: Matching last value in reg expression
by Abigail-II (Bishop) on Sep 30, 2003 at 14:04 UTC
    Well, it's a way, but I would write the block as:
    for (@files) { my @matches = /(.{8}-.{3}-i32)/g; my $last_match = $matches [-1]; print $last_match, "\n"; }

    You're not doing anything with $match, and I wouldn't assing the @_. Furthermore, why use @stats if all you care about is a single scalar? It's confusing and is less efficient. Also, if you are going to match against $_, no need to bind it. Note also that there is no need to backwhack a dash in a regular expression outside of character classes.

    But you can eliminate the intermediate array:

    my $last_match = (/(.{8}-.{3}-i32)/g) [-1];

    Or, if you are certain there is a match:

    1 while /(.{8}-.{3}-i32)/g; my $last_match = $1;
    You might even be able to use:
    my ($last_match) = /.*(.{8}-.{3}-i32)/;
    although in some cases that might be slower, or (in case of possible overlapping matches) give you a different answer.

    The latter two have the advantage that they don't create an intermediate array or list, which, if there are lots and lots of matches, could be a win.

    Abigail

      Thank you for you explanation.
Re: Matching last value in reg expression
by broquaint (Abbot) on Sep 30, 2003 at 14:02 UTC
    Just take advantage of the fact that a regex match in list context will return what was captured in the parentheses (if any) as a list e.g
    my($match) = reverse /(.{8}-.{3}-i32)/g;
    See. perlop for more info on the behaviour of m//. Also, you don't need to escape the dashes in that regex as they only have a special meaning in character class, see. perlre for more info.

    HTH

    _________
    broquaint