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

Dear Monks, I have a file that has comment lines (comment char is ">") and I want to read it all into an array.

The data looks something like

> comment 10 12 18 20 21 25 27 38 40 41 43 50
I read the file line by line (skipping the comment char) into an array,
while ( <INFILE> ) { next if ($_ =~ /^(\>)/); push @dat, $_; }
Id like each record in the file (excluding comment characters or newline characters) as an array element, so for my example data it would look like
@arr = (10, 12, 18, 20,21, 25, 27, 38,40, 41, 43, 50)
Is there a fast way to split array elements, other than what Ive done below?
my @arr; foreach (@dat) { my @a = split(//,$_); @arr = (@arr, @a); }
Thanks.

Replies are listed 'Best First'.
Re: split array elements
by roubi (Hermit) on Apr 17, 2009 at 03:09 UTC
    You don't need to recreate @arr for every line. This would be faster:
    my @arr; while ( <INFILE> ) { next if ($_ =~ /^(\>)/); push @arr, split(/ /, $_); }
Re: split array elements
by jwkrahn (Abbot) on Apr 17, 2009 at 05:37 UTC

    This should do what you want:

    while ( <INFILE> ) { next if /^>/; push @dat, split; }
Re: split array elements
by targetsmart (Curate) on Apr 17, 2009 at 09:33 UTC
    See; the monks only suggested while+push, but you have used while+push+foreach, so you could gain some speed if you use while+push.
    how you measured that the method you used is not fast, did you tried to benchmark?.

    Vivek
    -- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.
Re: split array elements
by GrandFather (Saint) on Apr 17, 2009 at 03:33 UTC

    Why is speed an issue? What are you not telling us that is the real problem?


    True laziness is hard work