in reply to writing to arrays

Try to base your code on the attached. Couple of things:
  1. You have to consider that, your data may come in out of sequence, DATA SET 10 might come before DATA SET 9, so you have to determine the index, before you can add the string to the array.
  2. Also you may have some data missing, for example, you may not have DATA SET 7 between DATA SET 6 and 8, you need to take this into consideration. Again this makes it a must for you to determine the index on fly.
  3. Is it possible for you to have the same DATA SET number more than once? For example, you had ">DATA SET 10", and later have "DATA SET 10" again. If yes, you have to think of a way to handle it base on the requirement. In my code, I just concat the latest with all old ones.
  4. In my code, I do not chomp away the newlines. If you want to remove them, uncomment that chomp.
  5. In my code, I left the array element at index zero undef all the time. If you want, you can use it, just substract 1 from the number you read from the file.
  6. in your m//, that \ before > is not needed, although it does not cause problem.
use Data::Dumper; use strict; my @data; my $cur_index; open(DATA, "<", "data.txt"); while (<DATA>) { #chomp; if (m/^>DATA SET (\d+)/) { $cur_index = $1; } else { $data[$cur_index] .= $_; } } close(DATA); print Dumper(@data);
(UPDATE: When the question was first posted, the data part was not well formatted as it is now, and my first solution assumed that the real data came right after the "DATA SET n", without line broken. Obviously that solution was wrong.

Thanks to gjb, he sent me a message, and pointed out that my solution didn't make sense to him. Then I checked the original question, and realized the format is now different after adding tags.

I really appreciate, not just gjb's tech point, but more important the way he handled it, which clearly shows his pleasant personality.)

Replies are listed 'Best First'.
Re: Re: writing to arrays
by Superman (Acolyte) on Dec 26, 2002 at 02:42 UTC
    thanks 4 ur reply but i think that what u r suggesting is a bit more complex than what i may actually need. Each line in my file is a $string, and what i need to do is to start at ">" and read every string i find from then into an @array until i find another ">"