endurocross has asked for the wisdom of the Perl Monks concerning the following question:

hello fellow coders
i have my little script , and i have to add an array to some existing array , can do no issue
the problem is when creating the array :

my @array= split (" ", "\n</body> \n</html>");


$array[0] and $array[1] , will also have "magically" escaped the "\n" character , i mean get it lost somewere in space
is there a way to split that string and let the "\n"'s in place ?

Replies are listed 'Best First'.
Re: (dont want) split to autoremove "\n"'s
by Athanasius (Archbishop) on Oct 10, 2014 at 13:02 UTC

    Hello endurocross, and welcome to the Monastery!

    Just change the pattern on which you are splitting. For example:

    22:59 >perl -MData::Dump -wE "my $s = qq[\n</body> \n</html>]; my @arr +ay = split(/[ \t]+/, $s); dd \@array;" ["\n</body>", "\n</html>"] 23:00 >

    Update 1: From the documentation for split:

    As another special case, split emulates the default behavior of the command line tool awk when the PATTERN is either omitted or a literal string composed of a single space character (such as ' ' or "\x20", but not e.g. / /). In this case, any leading whitespace in EXPR is removed before splitting occurs, and the PATTERN is instead treated as if it were /\s+/; in particular, this means that any contiguous whitespace (not just a single space character) is used as a separator. However, this special treatment can be avoided by specifying the pattern / / instead of the string " ", thereby allowing only a single space character to be a separator.

    Update 2: Changed /[ \t]/ to /[ \t]+/.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: (dont want) split to autoremove "\n"'s
by duelafn (Parson) on Oct 10, 2014 at 15:23 UTC

    You can use a Look-behind assertion to keep the newlines and the spaces:

    $ perl -MData::Dump -wE 'my $s = qq[\n</body> \n</html>]; my @array = +split(/(?<=\n)/, $s); dd \@array' ["\n", "</body> \n", "</html>"]

    Good Day,
        Dean