Search code examples
arraysperlsubroutine

Passing an array to a subroutine encloses it in another array?


I noticed that when I pass an array to my subroutine it seems like it gets encapsulated by another array (so two levels, while the initial is only one).

I know that using references to arrays is better, but I'm wondering in this specific case why it is not working as expected.

Code example:

#!/usr/local/bin/perl

use Data::Dumper;

sub testSub {
    my (@arr) = (@_);
    print Dumper \@arr;
}

my @testArray = ();
push @testArray, {
    'key1' => 'value1',
    'key2' => 'value2',
    'urls' => [ 'www.example.com' ]
};

print Dumper @testArray;

foreach my $item ( @testArray ) {

    my @urls = testSub( $item->{'urls'} );
}

output

$VAR1 = {
          'urls' => [
                      'www.example.com'
                    ],
          'key1' => 'value1',
          'key2' => 'value2'
        };
$VAR1 = [
          [
            'www.example.com'
          ]
        ];

Solution

  • my @urls = testSub( $item->{'urls'}, 'abc' );
    
    Result of Dumper in subrotine:
    $VAR1 = [
              [
                'www.example.com'
              ],
              'abc'
            ];
    

    Array passed by reference. Since at the time of compilation perl did not know what will be in the scalar $item->{'urls'}.

    my @urls = testSub( @{ $item->{'urls'} }, 'abc' );
    
    Result of Dumper in subrotine:
    $VAR1 = [
              'www.example.com',
              'abc'
            ];
    

    Now the compiler expects an array and turns it into a list.