5

I would expect the following code

my @array;
for my $rapport ( qw( value1 value2 value3 ) ) {
    push @array, { key => $rapport };
}

to produce:

$VAR1 = [
      {
        'key' => 'value1'
      },
      {
        'key' => 'value2'
      },
      {
        'key' => 'value3'
      }
    ];

However, running this code segment under Catalyst MVC I get:

$VAR1 = [
          {
            'key' => [ 'value', 'value2', 'value3' ]
          },
        ];

Can someone please explain to me why?

EDIT: could anyone with the same issue please add an example? I cannot reproduce after some code changes, but as it has been upvoted 5 times I assume some other users have also experienced this issue?

Mauritz Hansen
  • 4,674
  • 3
  • 29
  • 34
  • Sorry if I'm being daft. You mean running under Catalyst MVC? perl version? – mikew Oct 08 '13 at 21:14
  • 2
    Also, what happens if you try for my $rapport (@{['value1', 'value2' ..]}). It appears that $rapport is getting assigned an arrayref of [value1, value2, value3] and the loop is executing only once. Which would mean the push is not the culprit. – mikew Oct 08 '13 at 21:31
  • mikew, I have upvoted your comment. Your assumption is probably correct. I am unable to reproduce this now, having in the meantime changed the code. I am interested to know why the question was upvoted 3 times though ... – Mauritz Hansen Oct 13 '13 at 17:05
  • 1
    Everyone loves a good mystery? – mikew Oct 13 '13 at 17:12

1 Answers1

1

This code example...

#!/usr/bin/perl

use Data::Dumper;
my @input = ( "var1", "var2", "var3" );
my @array;
for my $rapport ( @input ) {
    push @array, { key => $rapport };
}

print Dumper( \@array );

exit;

produces ...

$VAR1 = [
          {
            'key' => 'var1'
          },
          {
            'key' => 'var2'
          },
          {
            'key' => 'var3'
          }
        ];

But the following...

#!/usr/bin/perl

use Data::Dumper;
my @input = [ "var1", "var2", "var3" ]; # sometimes people forget to dereference their variables
my @array;
for my $rapport ( @input ) {
    push @array, { key => $rapport };
}

print Dumper( \@array );

exit;

shows...

$VAR1 = [
          {
            'key' => [
                       'var1',
                       'var2',
                       'var3'
                     ]
          }
        ];

As you can see both examples loop through an array but the second one is an array, that was initialized with a reference value. Since in Catalyst you normally ship various values through your application via stash or similar constructs, you could check weather your array really contains scalar values : )

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • deviolog, I think you may be on to something. As I mention in my post, I no longer have the code so I cannot reproduce the issue. Your hypothesis seems very reasonable though. As there are no other answers I will accept this one. – Mauritz Hansen Dec 18 '13 at 13:20