CGI/Perl Guide | Learning Center | Forums | Advertise | Login Site Search: in Perl Guide PerlGuru Forums Learning Ctr
 MAIN INDEX SEARCHPOSTS WHO'S ONLINE LOG IN

Home: Perl Programming Help: Advanced:
Multi dimentional array problem

hydpm
User

Sep 6, 2009, 10:20 AM

Post #1 of 5 (2600 views)
 Multi dimentional array problem Can't Post
The reference is like below:

\$ref = [a,[b,c],d,[e,f]];

Then how to process arrays of such types of any depth like n-dimentional array?

The output should print elements like below after processing:

a

-b

-c

d

-e

-f

Nag

toolic
User

Sep 6, 2009, 11:17 AM

Post #2 of 5 (2596 views)
 Re: [wingsof5r] Multi dimentional array problem [In reply to] Can't Post
This works for your example:
 Code
`use warnings; use strict;   my \$ref = ['a',['b','c'],'d',['e','f']]; for my \$x (@{\$ref}) {    if (ref(\$x) eq 'ARRAY') {       for my \$y (@{\$x}) {          print "-\$y\n";       }    }    else {       print "\$x\n";    } }`

For deeper structures, you should consider recursion
or search on CPAN.

toolic
User

Sep 6, 2009, 12:25 PM

Post #3 of 5 (2592 views)
 Re: [toolic] Multi dimentional array problem [In reply to] Can't Post
... and here's a recursion example:
 Code
`use warnings;  use strict;     my \$ref = ['a',['b','c'],'d',['e',['y','z'],'f']];  my \$depth = 0;  process(\$ref);     sub process {     my \$aref = shift;     for my \$x (@{\$aref}) {        if (ref(\$x) eq 'ARRAY') {           \$depth++;           process(\$x);           \$depth--;        }        else {           print "\$depth \$x\n";        }     }  }     __END__  Prints out:  0 a  1 b  1 c  0 d  1 e  2 y  2 z  1 f`

If you just need to print out your data structure, you could use the core module, Data::Dumper.

(This post was edited by toolic on Sep 10, 2009, 9:30 AM)

hydpm
User

Sep 7, 2009, 7:00 AM

Post #4 of 5 (2572 views)
 Re: [toolic] Multi dimentional array problem [In reply to] Can't Post
Thank you very much for the help.

hydpm
User

Sep 7, 2009, 7:04 AM

Post #5 of 5 (2571 views)
 Re: [toolic] Multi dimentional array problem [In reply to] Can't Post
This logic, anyways, failing to handel more than 2 depths. Recursion one below working for any depths of arrays.

Thank you very much

Nag

 Announcements     PerlGuru Announcements Perl Programming Help     Frequently Asked Questions     Beginner     Intermediate     Advanced     Regular Expressions     mod_perl     DBI     Win32 Programming Help Fun With Perl     Perl Quizzes - Learn Perl the Fun Way     Perl Golf     Perl Poetry Need a Custom or Prewritten Perl Program?     I need a program that...     I Need a Programmer for Freelance Work     Throw Down The Gauntlet General Discussions     General Questions     Feedback     Tutorial/Article Suggestions for The Learning Cent     Internet Security Other Programming Languages     Javascript     PHP

 Search this forum this category all forums for All words Any words Whole Phrase (options) Powered by Gossamer Forum v.1.2.0