#!/Perl/bin/perl
package Test;
use strict;
use warnings;
use Perl6::Say;
use Data::Dumper qw/Dumper/;
sub new {
my $class = shift;
return bless({}, $class);
} # /new
sub run {
my $self = shift;
=comment
my $VAR1 = {'0' => [0,[[505,[[500,[[1],[2]]],[504,
[[3],[503,[[501,[[4],[5]]],[502,[[6],[507,[[7],[8]]]]]]]]]]],
[9]]],'500' => [500,[[1],[2]]],'501' => [501,[[4],[5]]],
'502' => [502,[[6],[507,[[7],[8]]]]],
'503' => [503,[[501,[[4],[5]]],[502,[[6],[507,[[7],[8]]]]]]],
'504' => [504,[[3],[503,[[501,[[4],[5]]],[502,[[6],[507,[[7],[8]]]]]]]]],
'505' => [505,[[500,[[1],[2]]],[504,[[3],[503,[[501,[[4],[5]]],
[502,[[6],[507,[[7],[8]]]]]]]]]]],'507' => [507,[[7],[8]]]};
=cut
my $all_subtrees = {
0 => [0, [[1], [2]]],
};
my $data = {
0 => {node => 'EOS'},
1 => {node => 'label', word => 'HELP'},
2 => {node => '.$', word => '!'},
};
say Dumper $self->translate_subtrees($all_subtrees, $data);
}
=head2 translate_subtrees( $all_subtrees, $data )
e.g.
my $all_subtrees = {
0 => [0, [[1],[2]]],
};
my $data = {
0 => {node => 'EOS'},
1 => {node => 'label', word => 'HELP'},
2 => {node => 'label' => '.$', word => '!'},
};
result:
my $trans = {
0 => ['EOS' [['label', 'HELP'], ['.$', '!']]]
};
=cut
sub translate_subtrees {
my $self = shift;
my $all_subtrees = shift;
my $data = shift;
my %translated = ();
while( my ($id, $subtree) = each %{$all_subtrees} ) {
my $subtree_flat = $self->flatten_array($subtree);
$subtree_flat =~ s/(.*[^0-9])([0-9])+([^0-9].*)/$1 ($2 >= 500 ? $data->{$2}->{node} : $data->{$2}->{node} . ' ' . $data->{$2}->{word} ) $3/g;
$translated{$id} = $subtree_flat;
}
return \%translated;
} # /translate_subtrees
=head2 flatten_array( $array_ref )
=cut
sub flatten_array {
my $self = shift;
my $a_ref = shift;
$Data::Dumper::Indent = 0;
my $flat = Dumper($a_ref);
$Data::Dumper::Indent = 2; # reset2new
return $flat;
} # /flatten_array
1;
use strict;
use warnings;
my $app = Test->new();
$app->run();