1

I need to fill some array with data and dump it to the screen. Here is the code:

my @a;

@a[0] = 69;
foreach $sibling ($someotherlist){
    my $cha = $sibling->{"id"} * 1;

    if (defined @a[$cha]){
        @a[$cha] = 0;
    }

    @a[$cha] = @a[$cha] + 1;
}
print Dumper(@a);

The problem is that it only prints $VAR1 = 69;
It should be something like:

$VAR1 = {
   0 => 69,
   1 => 30,
   20 => 90
}
4
  • 3
    You need to turn on use strict; use warnings;. You will then get at least one warning of Scalar value @a[0] better written as $a[0] Commented Nov 14, 2014 at 14:20
  • Tip: That * 1 is rather useless Commented Nov 14, 2014 at 14:44
  • Tip: if (defined $a[$cha]) { $a[$cha] = 0; } can be simplified to $a[$cha] //= 0;. If you don't want a dependency on Perl 5.10+, you can use $a[$cha] ||= 0; in this case. Commented Nov 14, 2014 at 14:44
  • Tip: $a[$cha] = $a[$cha] + 1; can be simplified to ++$a[$cha]. Commented Nov 14, 2014 at 14:46

3 Answers 3

6

Always use references with Data::Dumper, so

print Dumper(\@a);

See

Sign up to request clarification or add additional context in comments.

1 Comment

Except he wants to get a hash when he has an array... There's insufficient information to help him with that, though.
1

You might want to install Data::Printer which can be used via its DDP alias from the command line as -MDDP or as use DDP; inside an application. In your case:

use DDP; 

... # [rest of script] 

p @a ;

Data::Dumper remains the standard but DDP is quite useful and easily configurable. The colours and shiny things and p() shortcut :-) make DDP easy to use as a "visualization aid" for data structures.

Comments

0

I've become a big fan of

use JSON;
warn to_json(\%data,{canonical=>1,pretty=>1});

even though it's a mess of typing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.