my @names = qw( car carpet pet); my $goodnames = sub{ join( '|', map {quotemeta $_->[0] } sort { $b->[1] <=> $a->[1] } map { [$_, length ] } @_; ); }; # later... s/stuff (??{ $goodnames->(@names) }) stuff//; #### .