Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Fun little problem - just stick the parents in front of the children and clean it up at the end :)

#!/usr/bin/perl use strict; use warnings; use List::Util qw( uniq ); my $data = { 986172 => { cat_name => "Category1", cat_parent_id => "" }, 986176 => { cat_name => "Category2", cat_parent_id => 986172 }, 986177 => { cat_name => "Category3", cat_parent_id => 986176 }, 986178 => { cat_name => "Category4", cat_parent_id => 986177 }, }; my $string = join ',', find( keys %$data ); print "$string\n"; sub find { uniq map { my $ref = $data->{$_}; $ref ? ( find( $ref->{cat_parent_id} ), $ref->{cat_name} ) : () } @_; }

Or build a little prerequisite table and topologically extract the names one by one.

#!/usr/bin/perl use strict; use warnings; my $data = { 986172 => { cat_name => "Category1", cat_parent_id => "" }, 986176 => { cat_name => "Category2", cat_parent_id => 986172 }, 986177 => { cat_name => "Category3", cat_parent_id => 986176 }, 986178 => { cat_name => "Category4", cat_parent_id => 986177 }, }; my $parents = ''; for my $v ( values %$data ) { $parents .= $v->{cat_parent_id} ? $v->{cat_name} . ' ' . $data->{$v->{cat_parent_id}}{cat_name} . + "\n" : $v->{cat_name} . "\n"; } #print "$parents\n"; my @order; $parents =~ s/\b($1)\b//g, push @order, $1 while $parents =~ s/^(\w+)\ +h*\n//m; my $answer = join ',', @order; print "$answer\n"; $parents and die "loop in parents at\n$parents";

In reply to Re: Organizing data from a hash by tybalt89
in thread Organizing data from a hash by audioboxer

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2024-04-19 08:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found