in reply to Arrays of hashes which have arrays

Hello all,

As the other monks have answered your question, I thought I might offer a tip. When printing the contents of an array, or stringifying an array in general, it's a lot easier (and more idiomatic) to use join.

So instead of:

my $yy = $test->{'divs'}; foreach my $xx (@$yy) { print $xx."\n";}

try:

my $yy = $test->{'divs'}; print ((join "\n", @$yy) . "\n");
The extra parens are required to prevent print being interpreted as a function and seeing only the join, not the extra "\n".

You also might want to explore more about {} syntax for dereferencing structures. The Camel Book has an excellent overview of the various syntaxes. Here's an example, eliminating the need for $yy:

foreach my $xx (@{$test->{divs}}) { print $xx."\n";} print ((join "\n", @{$test->{divs}}) . "\n");
Of course, it can be argued that these sorts of idioms reduce legibility. It's a matter of taste.

--Clinton

Replies are listed 'Best First'.
Re^2: Arrays of hashes which have arrays
by johngg (Canon) on Jan 27, 2009 at 22:56 UTC
    my $yy = $test->{'divs'}; print ((join "\n", @$yy) . "\n");

    The extra parens are required to prevent print being interpreted as a function and seeing only the join, not the extra "\n".

    You only really need one pair of parentheses and those should be around the arguments to join, and the concatenation (.) would, I think, be better as a comma since print is happy to work with a list.

    my $yy = $test->{'divs'}; print join( "\n", @$yy ), "\n";

    Another way to do this is to localise the list separator to a newline and, as you say, avoid the $yy temporary variable.

    print do{ local $" = qq{\n}; qq{@{ $test->{ divs } }\n} };

    I hope this is of interest. (Note, the use of quoting constructs, q{...} instead of '...' and qq{...} instead of "..." is a habit of mine so that one-liners work in *nix shells and at MS command prompts.)

    Cheers,

    JohnGG