++ed by:
AERO KEEDI EMAZEP MOCNII AWNCORP

11 PAUSE users
8 non-PAUSE users.

Yingyao Zhou

NAME

Data::Table - Data type related to database tables, spreadsheets, CSV/TSV files, HTML table displays, etc.

SYNOPSIS

  # some cool ways to use Table.pm
  use Data::Table;
  
  $header = ["name", "age"];
  $data = [
    ["John", 20],
    ["Kate", 18],
    ["Mike", 23]
  ];
  $t = new Data::Table($data, $header, 0);      # Construct a table object with
                                        # $data, $header, $type=0 (consider 
                                        # $data as the rows of the table).
  print $t->csv;                        # Print out the table as a csv file.

  
  $t = Data::Table::fromCSV("aaa.csv");       # Read a csv file into a table object
  print $t->html;                       # Display a 'portrait' HTML TABLE on web. 

  use DBI;
  $dbh= DBI->connect("DBI:mysql:test", "test", "") or die $DBI::errstr;
  my $minAge = 10;
  $t = Data::Table::fromSQL($dbh, "select * from mytable where age >= ?", [$minAge]);
                                        # Construct a table form an SQL 
                                        # database query.

  $t->sort("age", 0, 0);                # Sort by col 'age',numerical,ascending
  print $t->html2;                      # Print out a 'landscape' HTML Table.  

  $row = $t->delRow(2);                 # Delete the third row (index=2).
  $t->addRow($row, 4);                  # Add the deleted row back as fifth row. 
  @rows = $t->delRows([0..2]);          # Delete three rows (row 0 to 2).
  $col = $t->delCol("age");             # Delete column 'age'.
  $t->addCol($col, "age",2);            # Add column 'age' as the third column
  @cols = $t->delCols(["name","phone","ssn"]); 
                                        # Delete 3 columns at the same time. 

  $name =  $t->elm(2,"name");           # Element access
  $t2=$t->subTable([1, 3..4],['age', 'name']);  
                                        # Extract a sub-table 

  $t->rename("Entry", "New Entry");     # Rename column 'Entry' by 'New Entry'
  $t->replace("Entry", [1..$t->nofRow()], "New Entry"); 
                                        # Replace column 'Entry' by an array of
                                        # numbers and rename it as 'New Entry'
  $t->swap("age","ssn");                # Swap the positions of column 'age' 
                                        # with column 'ssn' in the table.

  $t->colMap('name', sub {return uc});  # Map a function to a column 
  $t->sort('age',0,0,'name',1,0);       # Sort table first by the numerical 
                                        # column 'age' and then by the 
                                        # string column 'name' in ascending
                                        # order
  $t2=$t->match_pattern('$_->[0] =~ /^L/ && $_->[3]<0.2'); 
                                        # Select the rows that matched the 
                                        # pattern specified 
  $t2=$t->match_string('John');         # Select the rows that matches 'John'   
                                        # in any column

  $t2=$t->clone();                      # Make a copy of the table.
  $t->rowMerge($t2);                    # Merge two tables
  $t->colMerge($t2);

  $t = new Data::Table(                 # create an employ salary table
    [
      ['Tom', 'male', 'IT', 65000],
      ['John', 'male', 'IT', 75000],
      ['Tom', 'male', 'IT', 65000],
      ['John', 'male', 'IT', 75000],
      ['Peter', 'male', 'HR', 85000],
      ['Mary', 'female', 'HR', 80000],
      ['Nancy', 'female', 'IT', 55000],
      ['Jack', 'male', 'IT', 88000],
      ['Susan', 'female', 'HR', 92000]
    ],
    ['Name', 'Sex', 'Department', 'Salary'], 0);
  
  sub average {  # this is an subroutine calculate mathematical average, ignore NULL
    my @data = @_;
    my ($sum, $n) = (0, 0);
    foreach $x (@data) {
      next unless $x;
      $sum += $x; $n++;
    }
    return ($n>0)?$sum/$n:undef;
  }
  
  $t2 = $t->group(["Department","Sex"],["Name", "Salary"], [sub {scalar @_}, \&average], ["Nof Employee", "Average Salary"]);
  # For each (Department,Sex) pair, calculate the number of employees and average salary
  $t2 = $t2->pivot("Sex", 0, "Average Salary", ["Department"]);
  # Show average salary information in a Department by Sex spreadsheet

ABSTRACT

This perl package uses perl5 objects to make it easy for manipulating spreadsheet data among disk files, database, and Web publishing.

A table object contains a header and a two-dimensional array of scalars. Three class methods Data::Table::fromCSV, Data::Table::fromTSV, and Data::Table::fromSQL allow users to create a table object from a CSV/TSV file or a database SQL selection in a snap.

Table methods provide basic access, add, delete row(s) or column(s) operations, as well as more advanced sub-table extraction, table sorting, record matching via keywords or patterns, table merging, and web publishing. Data::Table class also provides a straightforward interface to other popular Perl modules such as DBI and GD::Graph.

The current version of Table.pm is available at http://easydatabase.googlepages.com

We use Data::Table instead of Table, because Table.pm has already been used inside PerlQt module in CPAN.

INTRODUCTION

    A table object has three data members:

    1. $data:

    a reference to an array of array-references. It's basically a reference to a two-dimensional array.

    2. $header:

    a reference to a string array. The array contains all the column names.

    3. $type = 1 or 0.

    1 means that @$data is an array of table columns (fields) (column-based); 0 means that @$data is an array of table rows (records) (row-based);

Row-based/Column-based are two internal implementations for a table object. E.g., if a spreadsheet consists of two columns lastname and age. In a row-based table, $data = [ ['Smith', 29], ['Dole', 32] ]. In a column-based table, $data = [ ['Smith', 'Dole'], [29, 32] ].

Two implementations have their pros and cons for different operations. Row-based implementation is better for sorting and pattern matching, while column-based one is better for adding/deleting/swapping columns.

Users only need to specify the implementation type of the table upon its creation via Data::Table::new, and can forget about it afterwards. Implementation type of a table should be considered volatile, because methods switch table objects from one type into another internally. Be advised that row/column/element references gained via table::rowRef, table::rowRefs, table::colRef, table::colRefs, or table::elmRef may become stale after other method calls afterwards.

For those who want to inherit from the Data::Table class, internal method table::rotate is used to switch from one implementation type into another. There is an additional internal assistant data structure called colHash in our current implementation. This hash table stores all column names and their corresponding column index number as key-value pairs for fast conversion. This gives users an option to use column name wherever a column ID is expected, so that user don't have to use table::colIndex all the time. E.g., you may say $t->rename('oldColName', 'newColName') instead of $t->rename($t->colIndex('oldColName'), 'newColIdx').

DESCRIPTION

Field Summary

data refto_arrayof_refto_array

contains a two-dimensional spreadsheet data.

header refto_array

contains all column names.

type 0/1

0 is row-based, 1 is column-based, describe the orientation of @$data.

Package Variables

$Data::Table::VERSION
@Data::Table::OK

see table::match_string and table::match_pattern

%Data::Table::DEFAULTS

Store default settings, currently it contains CSV_DELIMITER (set to ','), CSV_QUALIFER (set to '"'), and OS (set to 0). see table::fromCSV, table::csv, table::fromTSV, table::tsv for details.

Class Methods

Syntax: return_type method_name ( [ parameter [ = default_value ]] [, parameter [ = default_value ]] )

If method_name starts with table::, this is an instance method, it can be used as $t->method( parameters ), where $t is a table reference.

If method_name starts with Data::Table::, this is a class method, it should be called as Data::Table::method, e.g., $t = Data::Table::fromCSV("filename.csv").

Conventions for local variables:

  colID: either a numerical column index or a column name;
  rowIdx: numerical row index;
  rowIDsRef: reference to an array of column IDs;
  rowIdcsRef: reference to an array of row indices;
  rowRef, colRef: reference to an array of scalars;
  data: ref_to_array_of_ref_to_array of data values;
  header: ref to array of column headers;
  table: a table object, a blessed reference.

Table Creation

table Data::Table::new ( $data = [], $header = [], $type = 0, $enforceCheck = 1)

create a new table. It returns a table object upon success, undef otherwise. $data: points to the spreadsheet data. $header: points to an array of column names. A column name must have at least one non-digit character. $type: 0 or 1 for row-based/column-based spreadsheet. $enforceCheck: 1/0 to turn on/off initial checking on the size of each row/column to make sure the data arguement indeed points to a valid structure.

table table::subTable ($rowIdcsRef, $colIDsRef)

create a new table, which is a subset of the original. It returns a table object. $rowIdcsRef: points to an array of row indices. $colIDsRef: points to an array of column IDs. The function make a copy of selected elements from the original table. Undefined $rowIdcsRef or $colIDsRef is interpreted as all rows or all columns.

table table::clone

make a clone of the original. It return a table object, equivalent to table::subTable(undef,undef).

table Data::Table::fromCSV ($name_or_handler, $includeHeader = 1, $header = ["col1", ... ], {OS=>$Data::Table::DEFAULTS{'OS'}, delimiter=>$Data::Table::DEFAULTS{'CSV_DELIMITER'}, qualifier=>$Data::Table::DEFAULTS{'CSV_QUALIFIER'}, skip_lines=>0, skip_pattern=>undef})

create a table from a CSV file. return a table object. $name_or_handler: the CSV file name or an already opened file handler. If a handler is used, it's not closed upon return. $includeHeader: 0 or 1 to ignore/interpret the first line in the file as column names, If it is set to 0, the array in $header is used. If $header is not supplied, the default column names are "col1", "col2", ... optional named argument OS specifies under which operating system the CSV file was generated. 0 for UNIX, 1 for PC and 2 for MAC. If not specified, $Data::Table::DEFAULTS{'OS'} is used, which defaults to UNIX. Basically linebreak is defined as "\n", "\r\n" and "\r" for three systems, respectively.

optional name argument delimiter and qualifier let user replace comma and double-quote by other meaningful single characters. <b>Exception</b>: if the delimiter or the qualifier is a special symbol in regular expression, you must escape it by '\'. For example, in order to use pipe symbol as the delimiter, you must specify the delimiter as '\|'.

optional name argument skip_lines let you specify how many lines in the csv file should be skipped, before the data are interpretted.

optional name argument skip_pattern let you specify a regular expression. Lines that match the regular expression will be skipped.

The following example reads a DOS format CSV file and writes a MAC format:

  $t = Data::Table:fromCSV('A_DOS_CSV_FILE.csv', 1, undef, {OS=>1});
  $t->csv(1, {OS=>2, file=>'A_MAC_CSV_FILE.csv'});
  open(SRC, 'A_DOS_CSV_FILE.csv') or die "Cannot open A_DOS_CSV_FILE.csv to read!";
  $t = Data::Table::fromCSV(\*SRC, 1);
  close(SRC);

The following example reads a non-standard CSV file with : as the delimiter, ' as the qaulifier

  my $s="col_A:col_B:col_C\n1:2, 3 or 5:3.5\none:'one:two':'double\", single'''";
  open my $fh, "<", \$s or die "Cannot open in-memory file\n";
  my $t_fh=Data::Table::fromCSV($fh, 1, undef, {delimiter=>':', qualifier=>"'"});
  close($fh);
  print $t_fh->csv;
  # convert to the standard CSV (comma as the delimiter, double quote as the qualifier)
  # col_A,col_B,col_C
  # 1,"2, 3 or 5",3.5
  # one,one:two,"double"", single'"
  print $t->csv(1, {delimiter=>':', qualifier=>"'"}); # prints the csv file use the original definition

The following example reads bbb.csv file (included in the package) by skipping the first line (skip_lines=>1), then treats any line that starts with '#' (or space comma) as comments (skip_pattern=>'^\s*#'), use ':' as the delimiter.

  $t = Data::Table::fromCSV("bbb.csv", 1, undef, {skip_lines=>1, delimiter=>':', skip_pattern=>'^\s*#'});
table table::fromCSVi ($name, $includeHeader = 1, $header = ["col1", ... ])

Same as Data::Table::fromCSV. However, this is an instant method (that's what 'i' stands for), which can be inherited.

table Data::Table::fromTSV ($name, $includeHeader = 1, $header = ["col1", ... ], {OS=>$Data::Table::DEFAULTS{'OS'}, skip_lines=>0, skip_pattern=>undef})

create a table from a TSV file. return a table object. $name: the TSV file name or an already opened file handler. If a handler is used, it's not closed upon return.. $includeHeader: 0 or 1 to ignore/interpret the first line in the file as column names, If it is set to 0, the array in $header is used. If $header is not supplied, the default column names are "col1", "col2", ... optional named argument OS specifies under which operating system the TSV file was generated. 0 for UNIX, 1 for P C and 2 for MAC. If not specified, $Data::Table::DEFAULTS{'OS'} is used, which defaults to UNIX. Basically linebreak is defined as "\n", "\r\n" and "\r" for three systems, respectively. <b>Exception</b>: if the delimiter or the qualifier is a special symbol in regular expression, you must escape it by '\'. For example, in order to use pipe symbol as the delimiter, you must specify the delimiter as '\|'.

optional name argument skip_lines let you specify how many lines in the csv file should be skipped, before the data are interpretted.

optional name argument skip_pattern let you specify a regular expression. Lines that match the regular expression will be skipped.

See similar examples under Data::Table::fromCSV;

Note: read "TSV FORMAT" section for details.

table table::fromTSVi ($name, $includeHeader = 1, $header = ["col1", ... ])

Same as Data::Table::fromTSV. However, this is an instant method (that's what 'i' stands for), which can be inherited.

table Data::Table::fromSQL ($dbh, $sql, $vars)

create a table from the result of an SQL selection query. It returns a table object upon success or undef otherwise. $dbh: a valid database handler. Typically $dbh is obtained from DBI->connect, see "Interface to Database" or DBI.pm. $sql: an SQL query string. $vars: optional reference to an array of variable values, required if $sql contains '?'s which need to be replaced by the corresponding variable values upon execution, see DBI.pm for details. Hint: in MySQL, Data::Table::fromSQL($dbh, 'show tables from test') will also create a valid table object.

table Data::Table::fromSQLi ($dbh, $sql, $vars)

Same as Data::Table::fromSQL. However, this is an instant method (that's what 'i' stands for), whic h can be inherited.

Table Access and Properties

int table::colIndex ($colID)

translate a column name into its numerical position, the first column has index 0 as in as any perl array. return -1 for invalid column names.

int table::nofCol

return number of columns.

int table::nofRow

return number of rows.

scalar table::elm ($rowIdx, $colID)

return the value of a table element at [$rowIdx, $colID], undef if $rowIdx or $colID is invalid.

refto_scalar table::elmRef ($rowIdx, $colID)

return the reference to a table element at [$rowIdx, $colID], to allow possible modification. It returns undef for invalid $rowIdx or $colID.

array table::header ($header)

Without argument, it returns an array of column names. Otherwise, use the new header.

int table::type

return the implementation type of the table (row-based/column-based) at the time, be aware that the type of a table should be considered as volatile during method calls.

Table Formatting

string table::csv ($header, {OS=>$Data::Table::DEFAULTS{'OS'}, file=>undef, delimiter=>$Data::Table::DEFAULTS{'CSV_DELIMITER'}, qualifier=>$Data::Table::DEFAULTS{'CSV_QAULIFIER'}})

return a string corresponding to the CSV representation of the table. $header controls whether to print the header line, 1 for yes, 0 for no. optional named argument OS specifies for which operating system the CSV file is generated. 0 for UNIX, 1 for P C and 2 for MAC. If not specified, $Data::Table::DEFAULTS{'OS'} is used. Basically linebreak is defined as "\n", "\r\n" and "\r" for three systems, respectively. if 'file' is given, the csv content will be written into it, besides returning the string. One may specify custom delimiter and qualifier if the other than default are desired.

string table::tsv

return a string corresponding to the TSV representation of the table. $header controls whether to print the header line, 1 for yes, 0 for no. optional named argument OS specifies for which operating system the TSV file is generated. 0 for UNIX, 1 for P C and 2 for MAC. If not specified, $Data::Table::DEFAULTS{'OS'} is used. Basically linebreak is defined as "\n", "\r\n" and "\r" for three systems, respectively. if 'file' is given, the tsv content will be written into it, besides returning the string.

Note: read "TSV FORMAT" section for details.

string table::html ($colors = ["#D4D4BF","#ECECE4","#CCCC99"], $tag_tbl = {border => '1'}, $tag_tr = {align => 'left'}, $tag_th = {align => 'center'}, $tag_td = {col3 => 'align="right" valign="bottom"', 4 => 'align="left"'}, $l_portrait = 1 )

return a string corresponding to a 'Portrait/Landscape'-style html-tagged table. $colors: a reference to an array of three color strings, used for backgrounds for table header, odd-row records, and even-row records, respectively. A default color array ("#D4D4BF","#ECECE4","#CCCC99") will be used if $colors isn't defined.

$tag_tbl: a reference to a hash that specifies any legal attributes such as name, border, id, class, etc. for the TABLE tag.

$tag_tr: a reference to a hash that specifies any legal attributes for the TR tag.

$tag_th: a reference to a hash that specifies any legal attributes for the TH tag.

$tag_td: a reference to a hash that specifies any legal attributes for the TD tag.

Notice $tag_tr and $tag_th controls all the rows and columns of the whole table. The keys of the hash are the attribute names in these cases. However, $tag_td is column specific, i.e., you should specify TD attributes for every column separately. The key of %$tag_td are either column names or column indices, the value is the full string to be inserted into the TD tag. E.g., $tag_td = {col3 => 'align=right valign=bottom} only change the TD tag in "col3" to be &lt;TD align=right valign=bottom&gt;.

$portrait controls the layout of the table. The default is 1, i.e., the table is shown in the "Portrait" style, like in Excel. 0 means "Landscape".

Attention: You will have to escape HTML-Entities yourself (for example '<' as '&lt;'), if you have characters in you table which need to be escaped. You can do this for example with the escapeHTML-function from CGI.pm (or the HTML::Entities module).

  use CGI qw(escapeHTML);
  [...]
  $t->colMap($columnname, sub{escapeHTML($_)}); # for every column, where HTML-Entities occur.
string table::html2 ($colors = ["#D4D4BF","#ECECE4","#CCCC99"], $specs = {'name' => '', 'border' => '1', ...})

This method is deprecated. It's here for compatibility. It now simple call html method with $portrait = 0, see previous description.

return a string corresponding to a "Landscape" html-tagged table. This is useful to present a table with many columns, but very few entries. Check the above table::html for parameter descriptions.

Table Operations

int table::setElm ($rowIdx, $colID, $val)

modify the value of a table element at [$rowIdx, $colID] to a new value $val. It returns 1 upon success, undef otherwise.

int table::addRow ( $rowRef, $rowIdx = table::nofRow)

add a new row ($rowRef points to the actual list of scalars), the new row will be referred as $rowIdx as the result. E.g., addRow($aRow, 0) will put the new row as the very first row. By default, it appends a row to the end. It returns 1 upon success, undef otherwise.

refto_array table::delRow ( $rowIdx )

delete a row at $rowIdx. It will the reference to the deleted row.

refto_array table::delRows ( $rowIdcsRef )

delete rows in @$rowIdcsRef. It will return an array of deleted rows upon success.

int table::addCol ($colRef, $colName, $colIdx = numCol)

add a new column ($colRef points to the actual data), the new column will be referred as $colName or $colIdx as the result. E.g., addCol($aCol, 'newCol', 0) will put the new column as the very first column. By default, append a row to the end. It will return 1 upon success or undef otherwise.

refto_array table::delCol ($colID)

delete a column at $colID return the reference to the deleted column.

arrayof_refto_array table::delCols ($colIDsRef)

delete a list of columns, pointed by $colIDsRef. It will return an array of deleted columns upon success.

refto_array table::rowRef ($rowIdx)

return a reference to the row at $rowIdx upon success or undef otherwise.

refto_arrayof_refto_array table::rowRefs ($rowIdcsRef)

return a reference to array of row references upon success, undef otherwise.

array table::row ($rowIdx)

return a copy of the row at $rowIdx upon success or undef otherwise.

refto_hash table::rowHashRef ($rowIdx)

return a reference to a hash, which contains a copy of the row at $rowIdx, upon success or undef otherwise. The keys in the hash are column names, and the values are corresponding elements in that row. The hash is a copy, therefore modifying the hash values doesn't change the original table.

refto_array table::colRef ($colID)

return a reference to the column at $colID upon success.

refto_arrayof_refto_array table::colRefs ($colIDsRef)

return a reference to array of column references upon success.

array table::col ($colID)

return a copy to the column at $colID upon success or undef otherwise.

int table::rename ($colID, $newName)

rename the column at $colID to a $newName (the newName must be valid, and should not be identical to any other existing column names). It returns 1 upon success or undef otherwise.

refto_array table::replace ($oldColID, $newColRef, $newName)

replace the column at $oldColID by the array pointed by $newColRef, and renamed it to $newName. $newName is optional if you don't want to rename the column. It returns 1 upon success or undef otherwise.

int table::swap ($colID1, $colID2)

swap two columns referred by $colID1 and $colID2. It returns 1 upon success or undef otherwise.

int table::colMap ($colID, $fun)

foreach element in column $colID, map a function $fun to it. It returns 1 upon success or undef otherwise. This is a handy way to format a column. E.g. if a column named URL contains URL strings, colMap("URL", sub {"<a href='$_'>$_</a>"}) before html() will change each URL into a clickable hyper link while displayed in a web browser.

int table::colsMap ($fun)

foreach row in the table, map a function $fun to it. It can do whatever colMap can do and more. It returns 1 upon success or undef otherwise. colMap function only give $fun access to the particular element per row, while colsMap give $fun full access to all elements per row. E.g. if two columns named duration and unit (["2", "hrs"], ["30", "sec"]). colsMap(sub {$_->[0] .= " (".$_->[1].")"; } will change each row into (["2 hrs", "hrs"], ["30 sec", "sec"]). As show, in the $func, a column element should be referred as $_->[$colIndex].

int table::sort($colID1, $type1, $order1, $colID2, $type2, $order2, ... )

sort a table in place. First sort by column $colID1 in $order1 as $type1, then sort by $colID2 in $order2 as $type2, ... $type is 0 for numerical and 1 for others; $order is 0 for ascending and 1 for descending; Sorting is done in the priority of colID1, colID2, ... It returns 1 upon success or undef otherwise. Notice the table is rearranged as a result! This is different from perl's list sort, which returns a sorted copy while leave the original list untouched, the authors feel inplace sorting is more natural.

table::sort can take a user supplied operator, this is useful when neither numerical nor alphabetic order is correct.

  $Well=["A_1", "A_2", "A_11", "A_12", "B_1", "B_2", "B_11", "B_12"];
  $t = new Data::Table([$Well], ["PlateWell"], 1);
  $t->sort("PlateWell", 1, 0);
  print join(" ", $t->col("PlateWell"));
  # prints: A_1 A_11 A_12 A_2 B_1 B_11 B_12 B_2
  # in string sorting, "A_11" and "A_12" appears before "A_2";
  my $my_sort_func = sub {
    my @a = split /_/, $_[0];
    my @b = split /_/, $_[1];
    my $res = ($a[0] cmp $b[0]) || (int($a[1]) <=> int($b[1]));
  };
  $t->sort("PlateWell", $my_sort_func, 0);
  print join(" ", $t->col("PlateWell"));
  # prints the correct order: A_1 A_2 A_11 A_12 B_1 B_2 B_11 B_12
table table::match_pattern ($pattern, $countOnly)

return a new table consisting those rows evaluated to be true by $pattern upon success or undef otherwise. If $countOnly is set to 1, it simply returns the number of rows that matches the string without making a new copy of table. $countOnly is 0 by default.

Side effect: @Data::Table::OK stores a true/false array for the original table rows. Using it, users can find out what are the rows being selected/unselected. In the $pattern string, a column element should be referred as $_->[$colIndex]. E.g., match_pattern('$_->[0]>3 && $_->[1]=~/^L') retrieve all the rows where its first column is greater than 3 and second column starts with letter 'L'. Notice it only takes colIndex, column names are not acceptable here!

table table::match_string ($s, $caseIgnore, $countOnly)

return a new table consisting those rows contains string $s in any of its fields upon success, undef otherwise. if $caseIgnore evaluated to true, case will is be ignored (s/$s/i). If $countOnly is set to 1, it simply returns the number of rows that matches the string without making a new copy of table. $countOnly is 0 by default.

Side effect: @Data::Table::OK stores a true/false array for the original table rows. Using it, users can find out what are the rows being selected/unselected. The $s string is actually treated as a regular expression and applied to each row element, therefore one can actually specify several keywords by saying, for instance, match_string('One|Other').

table table::rowMask($mask, $complement)

mask is reference to an array, where elements are evaluated to be true or false. The size of the mask must be equal to the nofRow of the table. return a new table consisting those rows where the corresponding mask element is true (or false, when complement is set to true).

E.g., $t1=$tbl->match_string('keyword'); $t2=$tbl->rowMask(\@Data::Table::OK, 1) creates two new tables. $t1 contains all rows match 'keyword', while $t2 contains all other rows.

mask is reference to an array, where elements are evaluated to be true or false. The size of the mask must be equal to the nofRow of the table. return a new table consisting those rows where the corresponding mask element is true (or false, when complement is set to true).

E.g., $t1=$tbl->match_string('keyword'); $t2=$tbl->rowMask(\@Data::Table::OK, 1) creates two new tables. $t1 contains all rows match 'keyword', while $t2 contains all other rows.

table table::group($colsToGroupBy, $colsToCalculate, $funsToApply, $newColNames)

Primary key columns are specified in $colsToGroupBy. All rows are grouped by primary keys first. Then for each group, an array of subroutines (in $funsToAppy) are applied to corresponding columns and yield a list of new columns (specified in $newColNames).

$colsToGroupBy, $colsToCalculate are references to array of colIDs. $funsToApply is a reference to array of subroutine references. $newColNames are a reference to array of new column name strings. If specified, the size of arrays pointed by $colsToCalculate, $funsToApply and $newColNames should be i dentical. A column may be used more than once in $colsToCalculate.

E.g., an employee salary table $t contains the following columns: Name, Sex, Department, Salary. (see examples in the SYNOPSIS)

$t2 = $t->group(["Department","Sex"],["Name", "Salary"], [sub {scalar @_}, \&average], ["Nof Employee", "Average Salary"]);

Department, Sex are used together as the primary key columns, a new column "Nof Employee" is created by counting the number of employee names in each group, a new column "Average Salary" is created by averaging the Salary data falled into each group. As the result, we have the head count and average salary information for each (Department, Sex) pair. With your own functions (such as sum, product, average, standard deviation, etc), group method is very handy for accounting purpose.

table table::pivot($colToSplit, $colToSplitIsNumeric, $colToFill, $colsToGroupBy, $keepRestCols)

Every unique values in a column (specified by $colToSplit) become a new column. undef value become "NULL". If the column type is numeric (specified by $colToSplitIsNumeric), the new column names are prefixed by "oldColumnName=". The new cell element is filled by the value specified by $colToFill.

When primary key columns are specified by $colsToGroupBy, all records sharing the same primary key collapse into one row, with values in $colToFill filling the corresponding new columns. If $colToFill is not specified, a cell is filled with 1 if there is a corresponding data record in the original table.

$colToSplit and $colToFill are colIDs. $colToSplitIsNumeric is 1/0. $colsToGroupBy is a reference to array of colIDs. $keepRestCols is 1/0, by default is 0. If $keepRestCols is off, only primary key columns and new columns are exported, otherwise, all the rest columns are exported as well.

E.g., applying pivot method to the resultant table of the example of the group method.

$t2->pivot("Sex", 0, "Average Salary",["Department"]);

This creates a 2x3 table, where Departments are use as row keys, Sex (female and male) become two new columns. "Average Salary" values are used to fill the new table elements. Used together with group method, pivot method is very handy for account type of analysis.

Table-Table Manipulations

int table::rowMerge ($tbl)

Append all the rows in the table object $tbl to the original rows. The merging table $tbl must have the same number of columns as the original. It returns 1 upon success, undef otherwise. The table object $tbl should not be used afterwards, since it becomes part of the new table.

int table::colMerge ($tbl)

Append all the columns in table object $tbl to the original columns. Table $tbl must have the same number of rows as the original. It returns 1 upon success, undef otherwise. Table $tbl should not be used afterwards, since it becomes part of the new table.

table table::join ($tbl, $type, $cols1, $cols2)

Join two tables. The following join types are supported (defined by $type):

0: inner join 1: left outer join 2: right outer join 3: full outer join

$cols1 and $cols2 are references to array of colIDs, where rows with the same elements in all listed columns are merged. As the result table, columns listed in $cols2 are deleted, before a new table is returned.

The implementation is hash-join, the running time should be linear with respect to the sum of number of rows in the two tables (assume both tables fit in memory).

Internal Methods

All internal methods are mainly implemented for used by other methods in the Table class. Users should avoid using them. Nevertheless, they are listed here for developers who would like to understand the code and may derive a new class from Data::Table.

int table::rotate

convert the internal structure of a table between row-based and column-based. return 1 upon success, undef otherwise.

string csvEscape($rowRef)

Encode an array of scalars into a CSV-formatted string.

optional named arguments: delimiter and qualifier, in case user wants to use characters other than the defaults. The default delimiter and qualifier is taken from $Data::Table::DEFAULTS{'CSV_DELIMITER'} (defaults to ',') and $Data::Table::DEFAULTS{'CSV_QUALIFIER'} (defaults to '"'), respectively.

refto_array parseCSV($string)

Break a CSV encoded string to an array of scalars (check it out, we did it the cool way).

optional argument size: specify the expected number of fields after csv-split. optional named arguments: delimiter and qualifier, in case user wants to use characters other than the defaults. respectively. The default delimiter and qualifier is taken from $Data::Table::DEFAULTS{'CSV_DELIMITER'} (defaults to ',') and $Data::Table::DEFAULTS{'CSV_QUALIFIER'} (defaults to '"'), respectively.

string tsvEscape($rowRef)

Encode an array of scalars into a TSV-formatted string.

TSV FORMAT

There is no standard for TSV format as far as we know. CSV format can't handle binary data very well, therefore, we choose the TSV format to overcome this limitation.

We define TSV based on MySQL convention.

  "\0", "\n", "\t", "\r", "\b", "'", "\"", and "\\" are all escaped by '\' in the TSV file.
  (Warning: MySQL treats '\f' as 'f', and it's not escaped here)
  Undefined values are represented as '\N'.

INTERFACE TO OTHER SOFTWARES

Spreadsheet is a very generic type, therefore Data::Table class provides an easy interface between databases, web pages, CSV/TSV files, graphics packages, etc.

Here is a summary (partially repeat) of some classic usages of Data::Table.

Interface to Database and Web

  use DBI;

  $dbh= DBI->connect("DBI:mysql:test", "test", "") or die $DBI::errstr;
  my $minAge = 10;
  $t = Data::Table::fromSQL($dbh, "select * from mytable where age >= ?", [$minAge]);
  print $t->html;

Interface to CSV/TSV

  $t = fromCSV("mydata.csv");
  $t->sort(1,1,0);
  print $t->csv;

  Same for TSV

Interface to Graphics Package

  use GD::Graph::points;

  $graph = GD::Graph::points->new(400, 300);
  $t2 = $t->match('$_->[1] > 20 && $_->[3] < 35.7');
  my $gd = $graph->plot($t->colRefs([0,2]));
  open(IMG, '>mygraph.png') or die $!;
  binmode IMG;
  print IMG $gd->png;
  close IMG;

AUTHOR

Copyright 1998-2006, Yingyao Zhou & Guangzhou Zou. All rights reserved.

It was first written by Zhou in 1998, significantly improved and maintained by Zou since 1999. The authors thank Tong Peng and Yongchuang Tao for valuable suggestions. We also thank those who kindly reported bugs, some of them are acknowledged in the "Changes" file.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

Please send bug reports and comments to: easydatabase at gmail dot com. When sending bug reports, please provide the version of Table.pm, the version of Perl.

SEE ALSO

  DBI, GD::Graph.

1 POD Error

The following errors were encountered while parsing the POD:

Around line 1570:

You can't have =items (as at line 1574) unless the first thing after the =over is an =item