my $data = "first line second line third line last line"; my $data2 = $data; print "Case 1:\n\n"; foreach (1..8){ my $line = undef; #lexical variable! $line = $1 if $data2 =~ s/^([^\n]*)\n//; #assign to the lexical if (! defined $line && $data2 !~ /\n/){ $line = $data2; $data2 = undef; }; print "SPEC: ($line)($data2)\n"; }; print "\n=======\n\nCase 2:\n\n"; foreach (1..8){ my $line = $1 if $data =~ s/^([^\n]*)\n//; #make a lexical and assign to it if (! defined $line && $data !~ /\n/){ $line = $data; $data = undef; }; print "SPEC: ($line)($data)\n"; }; #### Case 1: SPEC: (first line)(second line third line last line) SPEC: (second line)(third line last line) SPEC: (third line)(last line) SPEC: (last line)() SPEC: ()() SPEC: ()() SPEC: ()() SPEC: ()() ======= Case 2: SPEC: (first line)(second line third line last line) SPEC: (second line)(third line last line) SPEC: (third line)(last line) SPEC: (last line)() SPEC: (last line)() SPEC: (last line)() SPEC: (last line)() SPEC: (last line)()