Link to home
Start Free TrialLog in
Avatar of sduser1
sduser1Flag for United States of America

asked on

Reading fields from the text file.

I need some help in getting all the fields without hardcording the count of the columns.

I have a text file which has 4 lines. Each line has 64 fields. I want to read each field and print it out.

I am hardcoding the count to be 256. Is there a way I can do it without hardcording the column count?

#!/usr/bin/perl
use strict;
use warnings;
open(FILE,$datafile) or die "No, can't open the file";
my $string;

while (<FILE>){
      $string .= $_;
       }

my @array = split(/\|/, $string);

for (my $i=0; $i <= 256; $i++) {

print "$array[$i]\n";

if ($array[$i] eq "") {
      
      print "No Value\n";
}
}
}#while loop
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Why are you concatenating file content into $string? That wastes memory.

 If you want to get the the four lines to be seen as one, you can keep count and check of it is modulus 4 at which point push(@array,$string) while $string is reset to''

it sounds as though you need a two dimensional array.

Could you post a sample of the data at least 5 lines at most 9.
Avatar of sduser1

ASKER

Thanks for the replies.  I am attaching the sample file.  One more thing.  The first line in the file is the header. The rest of the 4 lines are the data for the header.

I want to print the header along with the array contents.  The below line of code worked to display the contents of the array without hardcoding. Thank you.

print $_||"No Value","\n" for @array ;
$array[0] will contain the header fields.