Home > front end >  Why an array of array preserves my initial array?
Why an array of array preserves my initial array?

Time:05-23

So I have this fragment of code:

push @{$savedcallouts[-1]}, {
$funcnm => {
    matches => {%$captures},
    flags => [eval { @flags}]
}};
print Dumper \@{$savedcallouts[-1]};

Which gives the following result:

$VAR1 = [
          [
            {
              'normalexpr' => undef
            },
            {
              'normalexpr' => undef
            },
            {
              'ternaryexpr' => undef
            }
          ]
        ];

But if I remove the square brackets of flags => [eval { @flags}] (i.e. have flags => eval { @flags} - I get this:

$VAR1 = {
          'begin_binary' => {
                              'HASH(0x1038301c0)' => {
                                                       'ternaryexpr' => undef
                                                     },
                              'flags' => {
                                           'normalexpr' => undef
                                         },
                              'matches' => {}
                            }
        };

Any ideas why is this happening and how can I potentially avoid - i.e. have the array as hash field directly without artifacts or being an nested array.

CodePudding user response:

First of all, eval { } is useless here. @flags isn't going to throw any exceptions.[1]

So

flags => eval { @flags }

is a weird way of writing

flags => @flags

flags => @flags

is a shorthand for

"flags", @flags

which is

"flags", $flags[0], $flags[1], $flags[2], ...

which is

"flags"   => $flags[0],
$flags[1] => $flags[2],
...

have the array as hash field directly

The values of hash elements are scalars.

So you can store a reference to an array in a scalar, but you can't store an array in a scalars.


  1. Well, it's possible to add magic @flags that could. But would you really want to ignore this exception? I can't fathom why you used eval here.
  • Related