Advertisement
dsuveges

get_table.pl

Dec 12th, 2016
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.77 KB | None | 0 0
  1. use strict;
  2. use warnings;
  3. use Data::Dumper;
  4.  
  5. # A custom field separator can be set as a second command line argument:
  6. my $field_separator = $ARGV[1] ? $ARGV[1] : ";";
  7.  
  8. # The first command line argument is considered as input file:
  9. my $inputfile = $ARGV[0] ? $ARGV[0] : "termek.csv";
  10.  
  11. my %hash = ();
  12.  
  13. open ( my $INPUT, "<", $inputfile) || die "[Error] Input file ($inputfile) could not be opened.\n";
  14. while ( my $line = <$INPUT>){
  15.     # Input line example:
  16.     # 1;2004. 01.17 13:19;Eper;5997.35
  17.     chomp $line;
  18.     my ($index, $date, $item, $price) = split /$field_separator/, $line;
  19.  
  20.     next unless defined $price and defined $item;  # we skip all those lines where these fields are not given.
  21.     $hash{$item}{purchase_cnt} += 1;
  22.     $hash{$item}{price} += $price;
  23.  
  24. }
  25.  
  26. # Let's see how the read data looks like:
  27. # print Dumper %hash; # OK, it seems the file is read as expected!
  28.  
  29. # Now print the data:
  30. my $html = "<!DOCTYPE HTML>\n<html>\n<head><title>Summary table</title>\n</head>\n<body>"; # html header:
  31. $html .= "<table style=\"text-align:center;\">\n\t<tr style=\"font-weight: bold;\"><td>Item</td><td>Times purchased</td><td>Total price</td></tr>\n"; # table header
  32.  
  33. # Looping through all items:
  34. foreach my $item (keys %hash){
  35.     $html .= sprintf "\t<tr><td style=\"font-weight: bold;\">%s</td><td>%s</td><td>%s</td></tr>\n", $item, $hash{$item}{purchase_cnt}, $hash{$item}{price};
  36. }
  37.  
  38. $html .= "</table>"; # table close
  39. $html .= "\n</body>\n</html>"; # html close
  40.  
  41. print $html;
  42.  
  43.  
  44. __END__
  45.  
  46. the below one-liner was used to generate an input of 200 lines:
  47. perl -le '@a = qw(alma egres szolo szilva); $date = "2016.10.13 20:45"; while ( $i < 200 ){ $item = $a[rand @a]; $price = int(rand(100));$i++;print join ";", $i, $date,$item, $price}' > sample.data.csv
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement