Software Projects

Perl subroutine for building a GFF3-formatted key-value pair string

Posted in Uncategorized by rmt on April 23, 2011

This Perl subroutine creates strings for writing to the ninth column (the “attributes” column) of a GFF format file.

Start with a hash of the keys/values you want to add to the GFF3 attributes column. When calling the subroutine, pass it a reference to your hash like this:

my $attribs = &stringconcat(\%keyvalue);

The hash indices and hash values will respectively become the tags and values in the returned string.

# Forms a concatenated string of key/value pairs given a reference to
# a hash of key/value pairs.
#
# Return value:
#  A string with the key/value pairs concatenated with '=' and ';',
#  for example, "key1=value1;key2=value2;key3=value3" and with
#  the "Name" and "ID" key/value pairs at the beginning as required by
#  Apollo.
#
sub stringconcat {
  my(%keyvalue) = %{$_[0]};

  # Put the "ID" and "Name" fields at the beginning
  my $attribs = "";
  if (exists $keyvalue{'ID'}) {
    $attribs .= "ID=$keyvalue{'ID'}";
  }
  if (exists $keyvalue{'Name'}) {
    if (exists $keyvalue{'ID'}) {
      $attribs .= "\;";
    }
    $attribs .= "Name=$keyvalue{'Name'}";
  }

  # Form a string from the remaining key/value pairs
  foreach my $key (keys %keyvalue) {
    if ($key eq "Name" || $key eq "ID") {
      next;
    }
    $attribs .= "\;$key=$keyvalue{$key}";
    print "$key=$keyvalue{$key}\n" if DEBUG;
  }
  print "\n" if DEBUG;
  return $attribs;
}

Using this code snippet puts the “Name” and “ID” attributes first in the list, which seems to be required by Apollo in order to open the GFF file at all.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: