AndreiMotinga
AndreiMotinga

Reputation: 1043

Perl. how to open csv file, count how many rows and columns it has

I have a msft.csv file. Columns are separated by ",". which is actually a table. Can't post a picture, don't understand how to attach the file.

My task is:

  1. Open the file and count and print how many rows and columns it has. Columns are separated by ",".
  2. Open the file and print maximum, minimum for these columns: Open,High,Low,Close,Volume,Adj Close with the corresponding date
  3. Open the file and calculate and print average for these columns: Open,High,Low,Close,Volume,Adj Close

I have read some literature but I can't do anything useful. Actually all I was able to do is open the file and print it out.

I figured I should use Text::CSV module, but I can't figure the right syntax.

I worked through first 6 chapters here http://www.perl.org/books/beginning-perl/ I've also read some info on http://perldoc.perl.org/index.html
but so far I'm a zero.

If it's possible - it would be great to see the solution with/without using module. I'll try to figure what you've done there, but if it's not too much trouble, I'll appreciate if you can explain at least something.

Any advice on what literature I should read? Any useful links?

p.s English is my second language, so please forgive me my grammar.

p.p.s I can do smtg with text files, but I haven't seen a single table example.

Upvotes: 1

Views: 5176

Answers (1)

ptierno
ptierno

Reputation: 10074

Something like this should work for you:

#!/usr/bin/perl
use strict;
use warnings;

my $filename = 'test.txt';
my $line;
my $lines = 0;
my @columns;

open(my $fh, '<', $filename) or die "Can't open $filename: $!";

$line = <$fh>;
@columns = split(',', $line);
$lines++ while <$fh>;
close $fh;

print "$lines lines\n";
print scalar @columns . " columns\n";

Upvotes: 2

Related Questions