This is really quick and dirty. Basically, if we can assume that the format is very strict (values don't have any quoting, and commas and parentheses are always in sane places), you can just do some replacements on the input and then eval out a result.

use Data::Dumper; my $tree_in = '(A,(B,C))'; #my $tree_in = "((A,(B,((C,(D,E)),(F,G)))),H)"; $tree_in =~ s/([^,()]+)/\{VALUE=>"$1"\}/g; $tree_in =~ s/\(/\{LEFT=>/g; $tree_in =~ s/,/,RIGHT=>/g; $tree_in =~ s/\)/\}/g; print $tree_in, "\n"; my $tref = eval $tree_in; print Dumper $tref; __END__ {LEFT=>{VALUE=>"A"},RIGHT=>{LEFT=>{VALUE=>"B"},RIGHT=>{VALUE=>"C"}}} $VAR1 = { 'LEFT' => { 'VALUE' => 'A' }, 'RIGHT' => { 'LEFT' => { 'VALUE' => 'B' }, 'RIGHT' => { 'VALUE' => 'C' } } };

As I say, it's quick and dirty, there's no input validation, and the door's wide open to hostile inputs (think, "run arbitrary Perl code"). It wouldn't be too hard to put some rules on the front end to make some of these problems go away, but in the end you may be happier with a more complete parsing solution.


In reply to Re: Parsing newick trees by kyle
in thread Parsing newick trees by citromatik

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.