titus.andronicus titus.andronicus - 1 year ago 79
Perl Question

Get the number of columns in an ASCII file

I have found many questions regarding CSV files, but not regarding a normal ASCII file (

) file.

Assuming I have a subroutine
sub writeMyFile($data)
, which writes different values in an ASCII file
. Each column is then a value, which I want to plot in another subroutine
sub plotVals()
, but for that I need to know the number of columns of
, which is not always the same.

What is an easy an readable way in Perl to have the number of columns of an ASCII file

Some sample input/output would be (note: file might have multiple rows):


(first line on my_data1.dat) -19922 233.3442 12312 0 0
(first line on my_data2.dat) 0 0 0


(for my_data1.dat) 5
(for my_data2.dat) 3

Answer Source

You haven't really given us enough detail for any answer to be really helpful (explaining the format of your data file, for example, would have been a great help).

But let's assume that you have a file where the fields are separated by whitespace - something like this:

col1  col2 col3    col4   col5 col6 col7    col8

We know nothing about the columns, only that they are separated by varying amounts of white space.

We can open the file in the usual manner.

my $file = 'my_file.dat';
open my $data_fh, '<', $file or die "Can't open $file: $!";

We can read each record from the file in turn in the usual manner.

while (<$data_fh>) {
  # Data is in $_. Let's remove the newline from the end.
  # Here we do other interesting stuff with the data...

Probably, a useful thing to do would be to split the record so that each field is stored in a separate element of an array. That's simple with split().

# By default, split() works on $_ and splits on whitespace, so this is
# equivalent to:
# my @data = split /\s+/, $_;
my @data = split;

Now we get to your question. We have all of our values in @data. But we don't know how many values there are. Luckily, Perl makes it simple to find out the number of elements in an array. We just assign the array to a scalar variable.

my $number_of_values = @data;

I think that's all the information you'll need. Depending on the actual format of your data file, you might need to change the split() line in some way - but without more information it's impossible for us to know what you need there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download