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

Hi all! I'm a new Perl programmer and I'm trying to output combinations of numbers (1 to 10) to a file, but all I can get as output is a list of "ARRAY(0x4eeeec)" (for instance), both in the screen and written on the file. I've searched a little all over the place (Perl Monks included) but I can't find a similar situation / problem. Since I'm a new Perl user, I think my code is printing not an actual value but an address - I guess I'm misusing the iterator, but I can't find out why and how to fix it. Any help will be greatly appreciated. Thanks, Joćo Fernandes

#!/usr/bin/perl use strict; use warnings; use Algorithm::Combinatorics qw(combinations); my @data = qw(1 2 3 4 5 6 7 8 9 10); my $k = 4; open(my $output, ">", "combinations.txt") or die "Can't open combinati +ons.txt: $!"; my $iter = combinations(\@data, $k); while (my $combination = $iter->next) { print "$combination\n"; print $output "$combination\n"; } close $output or die "$output: $!";

Replies are listed 'Best First'.
Re: Misprinting combinations / iterator
by tangent (Parson) on Mar 27, 2012 at 15:36 UTC
    The $combination variable returned by the iterator is an array reference, so you need to de-reference it in order to print. The following will print each combination on a line, with each element separated by a tab character:
    print $output join("\t",@{$combination}) . "\n";
    The @{ } construct is what de-references the array reference
      Thanks for the explanation, tangent :]
Re: Misprinting combinations / iterator
by moritz (Cardinal) on Mar 27, 2012 at 15:36 UTC

    If you see something like ARRAY(0x4eeeec), it means you have an array reference. They are thoroughly explained in perllol and perlreftut.

    The fix is to dereferencing them before printing, for example print "@$combination\n";

      Thanks, moritz. I had already looked at perlol, but haven't understand it fully.

Re: Misprinting combinations / iterator
by Marshall (Canon) on Mar 27, 2012 at 15:54 UTC
    I haven't used this particular module, but from looking at the documentation.. $combination is a reference to an array (an arrayref) - that needs to be deferenced. print "@$combination\n"; looks like what you need.

      You're right, Marshall! Thank you all for your kind and quick answers! :]

        The examples in the module's docs weren't completely explanatory - I can see how this was confusing!

        There is a "core" module (meaning that is pre-installed and exists on all Perl installations), Data::Dumper. It can print a representation of any Perl data structure - WOW! You need to give it a reference to the structure.

        This is fantastic debugging tool.
        There is no equivalent in 'C' or 'Java' of which I am aware.

        use Data::Dumper; # in your loop put... print Dumper \$combination;