CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



hydpm
User

Sep 6, 2009, 10:20 AM

Post #1 of 5 (1718 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





Thanks in advance,

Nag


toolic
User

Sep 6, 2009, 11:17 AM

Post #2 of 5 (1714 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 (1710 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 (1690 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 (1689 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

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives