#!/usr/bin/perl use strict; use warnings; use diagnostics; my $B = ""; my $A = "abc def ghi "; while ( $A =~ m{(.+)}g ) { $B .= "$1\n" unless $1 =~ /def/; } print "\$B = \n$B\n"; $B = ""; while ( $A =~ m{(.+)}g ) { $B .= "$1\n" while $1 =~ /def/; } print "\$B = \n$B\n";