Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

How to print the deep content of the array?

by Anonymous Monk
on Sep 21, 2000 at 05:29 UTC ( [id://33437]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How can I accept an array as input and print out the deep content of the array?

my @ary = (1, ["a", "b", [ ], [3, [0],5]);

Would like to print out:

(1, [a, b, [ ], [3, [0], 5])

(formatting fixed by editors)

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How to print the deep content of the array?
by chromatic (Archbishop) on Sep 21, 2000 at 07:08 UTC
    If it doesn't need to be in that exact format, the built in Data::Dumper module is quite nice:
    use Data::Dumper; print Dumper(\@ary);
    Otherwise, you'll have to loop through the elements of the array, checking them with ref and recursing when necessary. It's doable, but not terribly fun.
Re: How to print the deep content of the array?
by princepawn (Parson) on Sep 21, 2000 at 16:51 UTC
    If using Data::Dumper as above, you will not have a descriptive name for the array. While this is not a problem when printing one variable, it can be when printing more. So, instead:
    @a=(1,2,3); $b= [ 4,5,6 ]; use Data::Dumper; Data::Dumper->Dump([\@a,$b],['a','b'])
Re: How to print the deep content of the array?
by ton (Friar) on Apr 05, 2001 at 03:35 UTC
    Of course it's more fun to do it yourself. Try this:
    my @ary = (1, ['a', 'b', [], [3, [0], 5]]); print_deep_array(\@ary); print "\n"; sub print_deep_array($) { my $arrRef = shift; for (my $i = 0; $i < scalar(@$arrRef); ++$i) { if (ref($arrRef->[$i]) eq 'ARRAY') { print ', ' if ($i); print '['; print_deep_array($arrRef->[$i]); print ']'; } else { print ', ' if ($i); print $arrRef->[$i]; } } print ' ' if (!scalar(@$arrRef)); }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://33437]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2024-04-26 01:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found