By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,178 Members | 971 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,178 IT Pros & Developers. It's quick & easy.

Problem reading a text file.

P: 68
Hi,

I'm facign a strange problem in reading a text file.

The contents of my text file is:

A1;B1;C1;D1
A2;B2;C2;D2
A3;B3;C3;D3


i want to split the contents based on the ";" (semi-colon).

I use the following code for it:

Expand|Select|Wrap|Line Numbers
  1.  
  2. open (OUT, "report.txt") || die "Can't open the File $!\n";
  3. my $data = <OUT>;
  4.  
  5.  
  6. my @values = split ";", $data;
  7. my $num = 0;
  8.  
  9. while($num < 12)
  10. {
  11.  
  12.     print $values[$num++];
  13.     print "<br>";
  14.  
  15. }
  16. close(OUT);
  17.  
  18. print "DONE!";
  19.  
  20.  
Im getting the following output:
--------------------------------
A1
B1
C1
D1







DONE!
---------------------------------

What surprises me, is why the remaining contents of $data is not stored in the "$values" array.

Another Question: if i try to split $data like this:

Expand|Select|Wrap|Line Numbers
  1. my @values = split "\n", $data;
  2.  
then, the output is:
------------------------------
A1;B1;C1;D1


DONE!
------------------------------

Can any1 tell me what could be the reason for the text after D1 not being displayed in both the cases.


Any help is appreciated.


Thanks,


Ravi
Jun 17 '08 #1
Share this Question
Share on Google+
2 Replies


KevinADC
Expert 2.5K+
P: 4,059
all this does is read the first line of the file:

Expand|Select|Wrap|Line Numbers
  1. my $data = <OUT>;
thats all your code ever does, is read the first line, process the first line, and ends.

You can do this to read the entire file into an array and then loop through the array to process the lines:

Expand|Select|Wrap|Line Numbers
  1. my @data = <OUT>;
  2.  
  3. for (@data) {
  4.    .....
  5. }
or process the file line by line:

Expand|Select|Wrap|Line Numbers
  1. while (my $data = <OUT>) {
  2.    .....
Jun 17 '08 #2

P: 68
Hey Kevin,

It works and fits my requirement too.

Thanks a lot.


Ravi
Jun 18 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.