Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Howto convert lines in stringified text into element of an array

by monkfan (Curate)
on Sep 04, 2007 at 03:22 UTC ( #636820=perlquestion: print w/ replies, xml ) Need Help??
monkfan has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
Suppose I have the following free text (it can be anything, e.g html,xml also), which is stringified into a variable $file:
my $file = 'foo bar qux foo foo foo ';
How can I convert it into array where each element contain each lines of the text above? into :
my $arry = [ 'foo', 'bar', 'qux', 'foo foo foo' ];

Regards,
Edward

Comment on Howto convert lines in stringified text into element of an array
Select or Download Code
Re: Howto convert lines in stringified text into element of an array
by ikegami (Pope) on Sep 04, 2007 at 03:33 UTC

    Assuming you want the same result as chomp( my @array = <FILE> );,

    chomp( my @array = $file =~ /\G(.*\n|.+)/g );

    or

    my @array = $file =~ /\G(?=.)([^\n]*)\n?/sg;

    or

    my @array = $file =~ /\G(.*)(?:\n|(?<=.))/g;

    or (This one allows you to easily use PerlIO layers)

    open my $fh, '<', \$file; chomp( my @array = <$fh> );

    If you want a reference to that array, use \:

    my $array = \@array;

    Update: Added variants.

Re: Howto convert lines in stringified text into element of an array
by GrandFather (Cardinal) on Sep 04, 2007 at 03:48 UTC
    use warnings; use strict; my $file = <<'FILE'; foo bar qux foo foo foo FILE my @lines = split $/, $file; print "$_\n" for @lines;

    Prints:

    foo bar qux foo foo foo

    DWIM is Perl's answer to Gödel
      Your solution truncates all trailing blank lines. That might be acceptable, but I'm mentioning it to let the OP (and other readers who might use this code) decide.
      my $file; my @data_lines; while (<DATA>) { $file .= $_; chomp; push @data_lines, $_; } my @split_lines = split $/, $file; print(scalar(@data_lines), "\n"); # 3 print(scalar(@split_lines), "\n"); # 2 __DATA__ foo bar

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://636820]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (8)
As of 2014-09-30 21:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (384 votes), past polls