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

Hi, I am trying to split a file into elements of an array everytime it comes across a new-line character.. I tried this;
my @array = split (/\n/, $array);
which doesn't work, can anyone suggest an alternative?? thanks

Replies are listed 'Best First'.
Re: splitting on new-line characters
by Abigail-II (Bishop) on Nov 28, 2002 at 11:40 UTC
    Could you be a bit more specific than "it doesn't work"? What is the content of $array? What is in @array after you did the split? What do you expect @array to contain?

    See, the line of code you gave means: split the content of $array on newlines, and put the resulting parts in @array.

    Abigail

Re: splitting on new-line characters
by broquaint (Abbot) on Nov 28, 2002 at 11:43 UTC
    Check $array actually has some newlines in it, as that code should work fine e.g
    my $str = <<TXT; foo bar baz TXT print "[$_]" for split /\n/, $str; __output__ [foo][bar][baz]

    HTH

    _________
    broquaint

Re: splitting on new-line characters
by UnderMine (Friar) on Nov 28, 2002 at 11:47 UTC
    Are you sure it is a new line? Careful when parsing files on a different platform from the one that generated it (ie. Unix file on Windows).

    Have you tried :-

    my @array = split /[\n\r\l]*/, $array;
    Hope it helps
    UnderMine
Re: splitting on new-line characters
by thinker (Parson) on Nov 28, 2002 at 11:42 UTC
    Hi AM,

    have you tried
    open FILE, "filename"; my @array = <FILE>;

    Hope this helps

    thinker
Re: splitting on new-line characters
by Ryszard (Priest) on Nov 28, 2002 at 11:52 UTC
    @ary = split(/0d0a/,unpack("H*",$array) );? :-)
      You will need to repack the data afterwards :-
      @array=map(pack('H*',$_),(split /0d0a/,unpack("H*",$array)));
      Hope it helps
      UnderMine