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



hydpm
User

Sep 6, 2009, 10:20 AM


Views: 2876
Multi dimentional array problem

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


Views: 2872
Re: [wingsof5r] Multi dimentional array problem

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


Views: 2868
Re: [toolic] Multi dimentional array problem

... 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


Views: 2848
Re: [toolic] Multi dimentional array problem

Thank you very much for the help.


hydpm
User

Sep 7, 2009, 7:04 AM


Views: 2847
Re: [toolic] Multi dimentional array problem

This logic, anyways, failing to handel more than 2 depths. Recursion one below working for any depths of arrays.

Thank you very much

Nag