while ( my $line = ) { chomp $line; # remove the spaces from start of line if ( $line =~ s/^\s+// ) { # print line if successful replacement print $line; } else { # print newline (not for first line) print "\n" if $. != 1; print $line; } } __DATA__ first second third first second third first second first #### while ( my $line = ) { chomp $line; # remove the spaces from start of line if ( ! ( $line =~ s/^\s+// ) ) { # print newline (not for first line) print "\n" if $. != 1; } print $line; }