in reply to Manually incrementing @ array during for

G'day cniggeler,

From your description, you're reading lines from a file and adding them to an array, then reading all the same lines from the array and processing them. You're doing the same work twice and you've provided no explanation why you need to do this. Is there a reason you're not just processing the lines as you read them from the file?

If your keyword lines all start the same -- e.g. "ID1", "ID2", etc. -- you can do something like this:

#!/usr/bin/env perl use strict; use warnings; { local $/ = 'keyword'; while (<DATA>) { next if $. == 1; chomp; y/\n//d; print "$/$_\n"; } } __DATA__ keyword1 data1 data2 data3 keyword2 data1 data2 data3 data4 data5 data6 keyword1 data1 data2 data3 data4 keyword3 data1

You may need to refer to local and, for $. and $/, "perlvar: Variables related to filehandles".

If the only way to differentiate keyword lines from continuation lines is by whitespace, you can do something like this:

#!/usr/bin/env perl use strict; use warnings; my $multiline = ''; while (<DATA>) { chomp; if (0 == index $_, ' ') { $multiline .= $_; } else { print "$multiline\n" if length $multiline; $multiline = $_; } } print "$multiline\n"; __DATA__ keyword1 data1 data2 data3 keyword2 data1 data2 data3 data4 data5 data6 keyword1 data1 data2 data3 data4 keyword3 data1

Both of those scripts produce identical output:

keyword1 data1 data2 data3 keyword2 data1 data2 data3 data4 data5 data6 keyword1 data1 data2 data3 data4 keyword3 data1

If there's something else going on here, you'll need to tell us. For instance, keyword may have some associated pattern, in which case a regex solution might be more appropriate.

Please include some code with any follow-up questions; along with output, even if that's only error messages.

— Ken

Replies are listed 'Best First'.
Re^2: Manually incrementing @ array during for
by AnomalousMonk (Archbishop) on Mar 17, 2020 at 15:11 UTC
    Is there a reason you're not just processing the lines as you read them from the file?

    According to this, the code for which cniggeler is responsible "... is part of a much bigger body of code, and I receive the already created @array, ... the @array may be used elsewhere." Then IIUC, it's not possible for cniggeler to parse the data at the point of access (which I agree would likely be simpler and more efficient).


    Give a man a fish:  <%-{-{-{-<

      Fair enough. I obviously missed the later post where the goal posts were moved. :-)

      The second of my two solutions would work equally well for an array. The chomp may not be necessary: hard to tell as the example input data presented in the OP looks more file data than array data.

      — Ken