This is quite a confusing, but interesting question. The idea is to build a second structure @tree that is a restructured version of @arr. @arr is assumed to be left as is?

The problem is that you are working with references to arrays, your are not copying the underlying arrays when you build @tree. So your line splice @{tree} ... is really inserting parts of @arr into the new variable and operate on them. If you replace this line by creating a copy of @$subNg and insert it into tree you should be fine (hopefully).

As a minor comment: I prefer to use Dumper \@arr as this creates a single structure and is more readable IMHO.

Proposed changes to leave @arr untouched:

$tree[0] = $arr[0]; my @copy = @{$arr[1]}; $tree[1] = \@copy; ... my ($index) = grep { $tree->[$_] eq $treeElement } 0..scalar(@$tre +e)-1; my @copy = @$subNg; splice @{$tree}, $index + 1, 0, \@copy;

Whether or not this modified code creates the desired @tree I do not know.


In reply to Re: Convert array to tree OR why variable changes arbitrarily by hdb
in thread Convert array to tree OR why variable changes arbitrarily by Anonymous Monk

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.