Tree datastructures: Difference between revisions

→‎{{header|Perl}}: native format / JSON
(→‎{{header|Perl}}: native format / JSON)
Line 164:
use warnings;
use feature 'say';
use JSON;
use Data::Printer;
 
my $trees = <<~END;
Line 187 ⟶ 189:
 
say my $indent = nested_to_indent $trees;
my $nest my $nest = indent_to_nested $indent;
 
use Test::More;
is($trees, $nest, 'Round-trip is good.');
done_testing();</lang>
 
# Import outline paragraph into native data structure
sub import {
my($trees) = @_;
my $level = ' ';
my $forest;
my $last = -999;
 
for my $branch (split /\n/, $trees) {
$branch =~ m/(($level*))*/;
my $this = $1 ? length($1)/length($level) : 0;
$forest .= do {
if ($this gt $last) { '[' . trim_and_quote($branch) }
elsif ($this lt $last) { ']'x($last-$this).',' . trim_and_quote($branch) }
else { trim_and_quote($branch) }
};
$last = $this;
}
sub trim_and_quote { shift =~ s/^\s*(.*\S)\s*$/"$1",/r }
 
eval $forest . ']' x (1+$last);
}
 
my $forest = import $trees;
say "Native data structure:\n" . np $forest;
say "\nJSON:\n" . encode_json($forest);</lang>
{{out}}
<pre>0 RosettaCode
1 encourages
2 code
Line 202 ⟶ 230:
2 trolling
2 emphasising execution speed
0 code-golf.io
1 encourages
2 golfing
Line 208 ⟶ 236:
2 comparison
 
ok 1 - Round-trip is good.
1..1
 
</pre>
Native data structure:
\ [
[0] "RosettaCode",
[1] [
[0] "encourages",
[1] [
[0] "code",
[1] [
[0] "diversity",
[1] "comparison"
]
],
[2] "discourages",
[3] [
[0] "golfing",
[1] "trolling",
[2] "emphasising execution speed"
]
],
[2] "code-golf.io",
[3] [
[0] "encourages",
[1] [
[0] "golfing"
],
[2] "discourages",
[3] [
[0] "comparison"
]
]
]
 
JSON:
["RosettaCode",["encourages",["code",["diversity","comparison"]],"discourages",["golfing","trolling","emphasising execution speed"]],"code-golf.io",["encourages",["golfing"],"discourages",["comparison"]]]</pre>
 
=={{header|Perl 6}}==
2,392

edits