use strict; use warnings; my $str = "aaa authentication login\r\n ssid Rich\r\n authentication open\r\n authentication shared \r\n"; my $authentication = ''; my @candidates = split /[\r\n] +/, $str; /^authentication\s+(\w*)(?{$authentication.= $1 . ' '})/ for @candidates; print $authentication; #### for (@candidates) { $authentication.= $1 . ' ' if /^authentication\s+(\w*)/; } #### open shared