The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


Data::Xtab - Pivot (cross-tabulate) a table of data.


This module allows you to feed it tables of data to be pivoted in such a way that they can be easily used in a report or graph. Here is an example of input data:

  'A', 'JUN', 7
  'A', 'JAN', 4
  'B', 'JAN', 3
  'B', 'FEB', 39
  'C', 'MAY', 8
  'A', 'JUN', 100

The output would be rendered as:

          JAN     FEB     MAR     APR     MAY     JUN
  A       4       0       0       0       0       107
  B       3       39      0       0       0       0
  C       0       0       0       0       8       0

The first column in the table ends up becoming the data series. The second column becomes the headers, under which the third column is summed. If more than one data records for the same data series and header column appear in the input data, the values are totalled for that intersection.

This module was designed to be used in conjunction with the GIFGraph module, but no doubt has other uses.



  use Data::Xtab;
  use GIFgraph::lines;
  use CGI;
  $query = new CGI;
  print $query->header("image/gif");

  my @data = ( ['A', 'FEB', 31],
               ['A', 'FEB', 12],
               ['A', 'MAR', 18],
               ['A', 'MAR', 29],
               ['A', 'APR', 142],
               ['B', 'FEB', 217],
               ['B', 'FEB', 14],
               ['B', 'MAR', 121],
               ['B', 'APR', 37],
               ['C', 'MAR', 39],
               ['C', 'MAR', 8],
               ['C', 'APR', 100] );

  # The outputcols parameter is used to enumerate the
  # columns that should be used in the output table, and
  # more importantly, the order in which they should appear.
  my @outputcols = ('JAN', 'FEB', 'MAR', 'APR');

  my $xtab = new Data::Xtab(\@data, \@outputcols);
  my @graph_data = $xtab->graph_data;

  $my_graph = new GIFgraph::lines();

  $my_graph->set( 'x_label' => 'Month',
                  'y_label' => 'Sales',
                  'title' => 'Monthly Sales',
                  'y_max_value' => 450,
                  'y_tick_number' => 5,
                  'y_label_skip' => 2 );
  print $my_graph->plot( \@graph_data );


Copyright (c) 1997, Brian Jepson You may distribute this kit under the same terms as Perl itself.