in reply to Converting Bracketted String (Newick's) into Array of Array
Try using this:
use strict; use warnings; use Data::Dumper; my $string="((mouse,rat),(human,chimp))"; my $tree=[]; die "Invalid char in input string" if $string !~ /^[(),\w]+$/; my @tokens=$string=~/(\(|\)|,|\w+)/g; my @stack=($tree); foreach (@tokens) { if ($_ eq '(') { my $new=[]; push(@{$stack[@stack-1]},$new); push(@stack,$new); } elsif ($_ eq ')') { die "Mismatched ')'" if @stack < 2; pop(@stack); } elsif ($_ ne ',') { push(@{$stack[@stack-1]},$_); } } die "Mismatched '('" if @stack != 1; $tree=$tree->[0]; print Dumper($tree);
Updated: added validity check on input string.
Rule One: "Do not act incautiously when confronting a little bald wrinkly smiling man."
|
|---|