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

hi, I wanna read each line of a file and then store every character on the line as an array element (including spaces). I have the following code. Which works fine it only does not catch the spaces in the sentence. Please let me know how to catch the spaces.
print "Program Running"; open FILE, "<Readme.txt" or die $!; my @lines = <FILE>; #while (lines = <FILE>) { print "Line is"; my $one= $lines[1]; print "first element only"; print $one; my @elements; ($elements[0],$elements[1],$elements[2],$elements[3],$elements[4])=spl +it(/ */,$one); print "after splitting"; print $elements[4]; } close FILE;

Replies are listed 'Best First'.
Re: Splitting each line into an array from file
by toolic (Bishop) on Jan 06, 2010 at 00:16 UTC
    This will also catch spaces (tabs, etc.):
    my @elements = split //, $one;
    This is explained in split
Re: Splitting each line into an array from file
by Marshall (Canon) on Jan 06, 2010 at 05:07 UTC
    I wrote this short thing below for you to further expand on toolic's post. turn CHOMP on and off and you will see what that does. Perl can processes lines character by character, but that is in practice seldom used because regex (regular expressions) are a built-in part of the language. You have an answer to your explicit question, but perhaps if you back up and explain what you are trying to accomplish, you might get a better solution to the overall problem.
    #!/usr/bin/perl -w use strict; print "Program Running\n"; # Below, I use the standard already opened DATA handle # instead of your open() # open FILE, "<", "Readme.txt" or die $! ; # the "=" stuff is a trick using a markup language # called perldoc to add text within the code so here # that the comment text doesn't get confused with the DATA. use constant CHOMP => 0; #change to 1 to see what happens while (<DATA>) { chomp if CHOMP; #deletes "new line" if enabled my @characters = split(//,$_); my $i=0; foreach my $char (@characters) { print $i++, " $char\n"; } } =Program Outputs the following: Program Running 0 S 1 o 2 m 3 e 4 5 S 6 t 7 u 8 f 9 f 10 Note: this is the \n in the input string followed by the \n in the print 0 a 1 s 2 d 3 f 4 =cut __DATA__ Some Stuff asdf