in reply to Looking for a good way to split a file into equal sized arrays

I agree that you need a flag to determine whether or not you are in a block, but beyond that, you need a datatype to hold all your data. I think you want an array of blocks that contains an array of lines that consists of an array of elements. This ought to do the trick:
use Data::Dumper; sub readFile{ open my $fh, "resource/datafile.txt" || die "Cannot open: $!"; @lines = <$fh>; $inblock = 0; my @block = [];shift @block; while($#lines >= 0){ my $single = shift @lines; print $single; if($single =~ /END DATA/){ $inblock = 0; push @allblocks,[@block]; @block = [];shift @block; } push @block,[split ' ',$single] if $inblock; $inblock = 1 if($single =~ /START DATA/); } } readFile; print Dumper(\@allblocks);
When a block starts the flag begins, and when a block ends the block is added to @allblocks. I don't consider myself a monk yet, but I tried the code and it works.

Replies are listed 'Best First'.
Re^2: Looking for a good way to split a file into equal sized arrays
by Luken8r (Novice) on Nov 26, 2007 at 21:21 UTC
    Thanks for all the suggestions, folks. While that flip flop did work out as anticipated, it turns out thats not exactly what I thought I needed
    What I ended up doing was sending all the data in the file to an array then incrementing the elements of that array in a for loop. Inside that for loop, I set a few triggers via a switch. Since the beginning value of each line tells me what sort of data it contains, I then split each line depending on what it was:
    {{{vars}}} my $infile = <STDIN>; print"Your input file is $infile\n\n"; open (INFILE, "<$infile")||die "no such file"; while (<INFILE>) { @data = <INFILE>; for ($x = 0; $x<=$#data; $x++){ chomp ($data[$x]); switch ($data[$x]){ # If start of section, increment array by 3 to skip header # case /^Begin Targets/ { $x += 3; } case /^0 / { # do not want last; } case /^1 / { @line = split(/ /,$data[$x]); # Get data out last; } case /^2 / { @line = split(/ /,$data[$x]); # Get data out last; } case /^3 / { @line = split(/ /,$data[$x]); # Get data out last; } # end case3 } # end switch } # end for } #end
    In each case I can take the line and set it to some variable depending on which place in the field I want,
    $DistX[$x] = $line[2]; $DistY[$x] = $line[3];
    ...etc
    Well Im half way there, Now I just need to output this data to a csv spreadsheet to plot it...but thats for tomorrow :)