Perl Advent Calendar 2010-12-18

On the 2nd day of Xmas Santa hits the bar pretty hard!

by Adam Russell

Re: the ordinal in the title, Christmastide begins on the 25th and runs though Epiphany.

Santa is truly a big picture guy. He prefers to get a sense of data quickly to make the important executive decisions, so the NMS needs to be able to provide a summary of the available data. Nick also gets increasingly impatient as the big day fast approaches, and yearns for figures on how the tallies of who has been naughty and nice are shaping up in order to place the final just-in-time toy orders

As very straightforward module without much mystery to it, Text::BarGraph fits the bill nicely. Even Santa's most junior elf can whip up a small bit of code to query the NMS and produce an easy to decipher ASCII-art chart. The naughty nice tally is an ongoing work with data being fed constantly into a database from around the world. Since this reporter has been sworn to secrecy concerning this most valuable of data stores, the sample code below contains only some static sample data reflecting a recent snapshot.

unknown (129398430) *********
naughty (233314664) *****************
   nice (456089984) *********************************

Using Text::BarGraph is as simple as constructing a hash for your data and passing your BarGraph object's graph() method a reference to it. You can also change the graphing character, sort records, and set the max data value to scale the chart width, among other adjustments. Perhaps of most use is the ability to display the graph bars in color—in segments as wide as 25% of the maximum width of the graph—if Term::ANSIColor is available

   1 # Let's make some ascii bar charts! 
   2 # Adam Russell
   4 use Text::BarGraph;
   6 my(%naught_nice, $total);
   7 my $graph = Text::BarGraph->new();
   8 while (my $line = <DATA>) {
   9     chomp $line;
  10     my @fields=split(/:/,$line);
  11     $total += $naught_nice{$fields[0]}=$fields[1];
  12 }
  13 $graph->dot("*");
  14 $graph->enable_color(1);
  15 $graph->max_data($total);
  16 $graph->sortvalue("data");
  17 print $graph->graph(\%naught_nice);
  19 __DATA__
  20 naughty:233314664
  21 nice:456089984
  22 unknown:129398430
View Source (POD)