in reply to Matching and replacing the minimum string from the tail of the regex

If your data set is small, and I guess it is as you are reading all of your lines into a single string, you could use grep to just get the lines that match a regex alternation of what you want then use another grep with a post-incremented hash so that you only get the one 's' line rather than all three.

use strict; use warnings; my %seen = (); print grep { ! $seen{$_} ++ } grep { m{^s|foo|e f$} } <DATA> __END__ s erartt e p s foo e f s adflkja

This produces

s foo e f

as you require. The more usual idiom for reading all lines of a file into a single string (slurping) is

my $lines = ''; { local $/; $lines = <DATA>; }

which changes the default input record separator inside the scope of the code block to undef so that the whole of the file is read into $lines in one fell swoop.

I hope this is of use.

Cheers,

JohnGG

Update: I should have placed the regex alternation in a non-capturing group. As it is, it matches lines beginning with 's', lines containing 'foo' anywhere and lines ending with 'e f'. Correct pattern is m{^(?:s|foo|e f)$}.