If you want to make it without a loop, you will need the /g
regex modifier.
This will get you all the repeating string:
my @str = $string =~ /(\S+)(?=\s\1)/ig;
I have replaced \w
with \S
(in your example, \w
doesn't match -
), and used a look-ahead: (?=\s\1)
means match something that is before \s\1
, without matching \s\1
itself—this is required to make sure that the next match attempt starts after the first string, not after the second.
Then, it is simply a matter of extracting the longest string from @str
:
my $longest = (sort { length $b <=> length $a } @str)[0];
(Do note that this is a legible but far from being the most efficient way of finding the longest value, but this is the subject of a different question.)