Tab delineated file
Tab delineated files put tables of information into lines where each field is separated by a tab. The first line can be a header file giving titles or names to the columns.
Contents |
[edit] 1 Advantages over CSVs
CSV files are also very common--but sometimes commas need to be a part of the fields, and it's harder to find an appropriate replacement. Tabs, however, can generally be replaced with a set of spaces in fields containing them with no ill effects.
[edit] 2 Perl
[edit] 2.1 Splitting the fields of the line into an array
my @line_fields = split( /\t/, $line );
[edit] 2.2 A subfunction to return a hash reference out of a line
# Input 1 # Line to split into fields # Input 2 # A list of headers in an array # Returns # A hash reference where each value of the line is accessible # by its column name, determined by the order of the list of # headers. sub get_fields { my $line = shift( @_ ); chomp( $line ); my @line_fields = @_; my @fields = split( /\t/, $line ); my %fields; foreach my $field_name (@line_fields) { $fields{$field_name} = shift( @fields ); } return \%fields; }
[edit] 2.3 A subfunction to make a tab delineated line from a hash reference given a list of columns
# Input 1 # A hash reference where the key is the name of the # column field and the value is that column's value # for this line # Input 2 # An array of column header names. This will be the # order for the columns used to make the lines. If not # present, will sort the keys of the hash and use that # instead. # Returns # A line of tab delineated values in the order of the # column header names given. sub make_line { my $hash = shift( @_ ); my @fields = @_; my @line; # if there are no specific fields, use the keys of the hash, sorted if( scalar( @fields ) == 0 ) { @fields = sort(keys(%$hash)); } foreach my $field ( @fields ) { push( @line, $hash->{$field} ); } return join( "\t", @line ) . "\n"; }