in reply to A maybe(?) interesting comp-sci type problem

sub flatten { my @ret = (); while (@_) { my $k = shift; if (ref $_[0]) { my $v = shift; push @ret, [ $k, @$_ ] for flatten(@{$v}); } else { push @ret, [ $k ]; # push @ret, [ shift ] while @_ and (! $_[1] or ! ref $_[1] +); } } @ret; } use Data::Dumper; print Dumper([flatten(@{$data_struct})]);

update: flattened code (see below :)

--shmem

_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                              /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

Replies are listed 'Best First'.
Re^2: A maybe(?) interesting comp-sci type problem
by ikegami (Patriarch) on May 06, 2008 at 09:26 UTC

    Two quick notes:

    Your inner while is redundant with your outer while. You can get rid of
    push @ret, [ shift ] while @_ and (! $_[1] or ! ref $_[1]);

    It wouldn't have hurt to note that your function destroys the original data structure.

    Update: Me bad.

      It wouldn't have hurt to note that your function destroys the original data structure.

      No, it doesn't. It doesn't operate directly on $_[n], but makes copies. The original is untouched.

      --shmem

      _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                    /\_¯/(q    /
      ----------------------------  \__(m.====·.(_("always off the crowd"))."·
      ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}