LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Writing Hashes with Text::CVS (Perl Code) (https://www.linuxquestions.org/questions/programming-9/writing-hashes-with-text-cvs-perl-code-4175498207/)

HyperTrey 03-14-2014 01:20 PM

Writing Hashes with Text::CVS (Perl Code)
 
Code:

use Text::CSV;
open my $file, ">", "StaffPrinting.csv" or die "Couldn't open location file: $!";
my @names = ("Username", "Black and White", "Color", "Ricoh", "Total Page Count");
my @lines = ("========", "===============", "=====", "=====", "================");

my %data;
my $csv = Text::CSV->new () or die;
$csv->eol ("\n");

$csv->print ($file, \@names);
$csv->print ($file, \@lines);

while(<>)  {
  @a = Parse_Log($_);
  ($uname, $queue, $pages) = ((lc($a[5])), (uc($a[4])), $a[10]);
  $prn = (split(/-/, $queue))[3];
  chop($prn);   

  $s = "\$" . "$prn" . "_amt{'$uname'} += $pages";
  eval($s); 
  $tot_page_count{$uname} = $BW_amt{$uname} + $CL_amt{$uname} + $RC_amt{$uname};

  # If an entry does not exist yet, create a blank one
  if(not exists $data{$uname}) {
    $data{$uname} = {};
  }

  $data{$uname}{BW_amt} = $BW_amt{$uname};
  if ($data{$uname}{BW_amt} eq "" ) { $data{$uname}{BW_amt} = 0; }
 
  $data{$uname}{CL_amt} = $CL_amt{$uname};
  if ($data{$uname}{CL_amt} eq "" ) { $data{$uname}{CL_amt} = 0; }
 
  $data{$uname}{RC_amt} = $RC_amt{$uname};
  if ($data{$uname}{RC_amt} eq "" ) { $data{$uname}{RC_amt} = 0; }

  $data{$uname}{tot_page_count} = $tot_page_count{$uname};
}
foreach (sort by_total_then_username keys %data) {
  $row = "$_,$data{$_}{BW_amt},$data{$_}{CL_amt},$data{$_}{RC_amt},$data{$_}{tot_page_count}\n";
  $csv->print ($file, $row);
}

sub by_total_then_username {
  return $data{$a}{tot_page_count} <=> $data{$b}{tot_page_count} ||
        $a cmp $b;
}
close $file or die "$!";

Obviously there is some not so pretty ways of accomplishing steps here, but I am editing someone else code and finishing the steps needed to complete before I go back and "pretty up" the code.

The issue is in the "$csv->print ($file, $row); ". How would I get $csv->print to print hashes to the csv file? And How would I get the columns to fit the data?

chrism01 03-16-2014 04:48 AM

Well the CPAN module page http://search.cpan.org/~makamaka/Tex...t/CSV.pm#print says it expects an io object and an array ref, pretty much as you have done.
Perhaps you could expand on your requirement ?
If your actual src will be a hash, you'll have to convert it for output.


All times are GMT -5. The time now is 10:00 PM.