Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Parsing a Tree to a Table.

by LanX (Chancellor)
on Dec 10, 2013 at 14:26 UTC ( #1066436=note: print w/replies, xml ) Need Help??

in reply to Parsing a Tree to a Table.

As a side note @RosettaStone: Many languages just showed their Data::Dumper equivalent! :-|

my emphasize is on readability and flexibility for alternative formats, but YMMV! =)

#!/usr/bin/perl use warnings; use strict; use Data::Dump qw/pp/; #use diagnostics; use Test::More tests => 1; my $input = <<'__IN__'; A | |--B | | | |--C | | | |---PQR | |---XYZ |--D | | | |---LMN |---XYZ __IN__ my $expected = <<'__EXP__'; Column1 Column2 Column3 Column4 A B C PQR A B C XYZ A D LMN A XYZ __EXP__ my (@path,@table); my $max=0; for (split /\n/, $input) { #print ; /^ (.*?) (---(\w\w\w))? $ /x; my $leave = $3; my @track = split / |--/, $1; die "parsing error $_" unless @track; $path[$#track] = $1 if ($track[-1] =~ /(\w)/ ); #pp [@track], [@path], $leave; if ($leave) { push @table, [ @path[0..$#track], $leave ]; $max = @track if @track >$max; } } pp \@table; my $out=""; $out .= "Column$_\t" for 1..$max+1; $out .= "\n"; for (@table){ my $width = @$_-1; $out .= join "\t", @$_[0..$width-1]; $out .= "\t"x($max-$width+1); $out .= @$_[$width]; $out .= "\n"; } print $out; is($out,$expected);

1..1 [ ["A", "B", "C", "PQR"], ["A", "B", "C", "XYZ"], ["A", "D", "LMN"], ["A", "XYZ"], ] Column1 Column2 Column3 Column4 A B C PQR A B C XYZ A D LMN A XYZ

Cheers Rolf

( addicted to the Perl Programming Language)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1066436]
[LanX]: hm just read an article on claiming that RPerl is 250 times faster. ... it's that even possible?
[marto]: under certain circumstances perhaps
[RonW]: as I understand it, RPerl "compiles" a subset of Perl to C, so I would expect the final executable to run a lot faster
[RonW]: Is there an English language version of the site?
[LanX]: but Afaik Perl is on average about 10-20 times slower than C
[LanX]: no

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2017-05-22 20:15 GMT
Find Nodes?
    Voting Booth?