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

I was looking for some help from the wise monks. I have a file that I read in and then break into an array based on its location in the file. I need to make an index so that I can sort the file and then pull out any record I need based on the index. I am kind of stumped and would appreciate any help. Here is what I have started so far, please forgive the childlike coding.
sub Read_File { $Index = 1; while(<CLAIMS>) { chomp; $FirstItem[$FirstItem[$Index]] = substr($_,1,8); $SecondItem[$SecondItem[$Index]] = substr($_,9,6); $ThirdItem[$ThirdItem[$index]] = substr($_,15,2); #File continues ad nauseum but you get the idea $Index++; }
Any suggestions to get me heading in the right direction would be appreciated. Prince99 Too Much is never enough...

Replies are listed 'Best First'.
(boo)Re: indexing an array
by boo_radley (Parson) on Apr 05, 2001 at 19:53 UTC
      In fact, with unpack you don't even need to chomp... in your case you don't need to chomp... why take the extra time when you are never going to read that far into the string?
                      - Ant
Re: indexing an array
by tadman (Prior) on Apr 05, 2001 at 20:35 UTC
    What exactly is intended by the recursive reference:          $FirstItem[$FirstItem[$Index]] That seems kind of unusual.

    As mentioned, unpack would do the job for you quite well, but even better would be to use a multi-dimensional array, or Array of Arrays (AoA), or even an Array of Hashes (AoH). AoH allows you to label the fields. AoA is probably more compact.

    Consider:
    sub Read_File { while(<CLAIMS>) { # (Choose one method only) # 1: AoH method my (%row); @row{'a','b','c'} = unpack ("A8 A6 A2", $_); push (@data, \%row); # 2: AoA method push (@data, [unpack ("A8 A6 A2", $_)]); } }
    So you can extract records like so:
    my ($record) = $data[$n]; # Index starts at 0, not 1 # AoH print "$record->{a} | $record->{b} | $record->{c}\n"; # AoA print "$record->[0] | $record->[1] | $record->[2]\n";
Re: indexing an array
by Tortue (Scribe) on Apr 05, 2001 at 20:41 UTC
    This may help get you started if you have trouble with unpack :
    sub Read_File { # An array of arrays to store the results my @items = (); while(<CLAIMS>) { # Extract the three fields into an array # and store a reference to it in @items push @items, [unpack("a8a6a2", $_)]; } # Display (for example) the 3d field in the 2nd line: print $items[1][2]; }
    Updated : This is the same as tadman's AoA solution above and mr.nick's below...
Re: indexing an array
by mr.nick (Chaplain) on Apr 05, 2001 at 20:46 UTC
    Something like this would suffice (using the unpack method as mentioned above):
    sub Read_file { ## we assume CLAIMS is a valid filehandle ## and @array is a global while (<CLAIMS>) { push @array,[unpack("a8a6a2",$_)]; } }
    Then you can access the information via $array[$linenumber]->[$itemnumber].

    (untested, btw, but it should work).