Search code examples
arraysperlreferenceperl-data-structures

I don't understand this Perl Syntax, has anyone got any idea?


I have got this part from a Perl plugin. I don't understand what it does. Is it an array of associative arrays? If so, then shouldn't it be started with @? Can anyone shed some light on this issue?

my $arguments =
  [ { 'name' => "process_exp",
    'desc' => "{BasePlugin.process_exp}",
    'type' => "regexp",
    'deft' => &get_default_process_exp(),
    'reqd' => "no" },
  { 'name' => "assoc_images",
    'desc' => "{MP4Plugin.assoc_images}",
    'type' => "flag",
    'deft' => "",
    'reqd' => "no" },
  { 'name' => "applet_metadata",
    'desc' => "{MP4Plugin.applet_metadata}",
    'type' => "flag",
    'deft' => "" },
  { 'name' => "metadata_fields",
    'desc' => "{MP4Plugin.metadata_fields}",
    'type' => "string",
    'deft' => "Title,Artist,Genre" },
  { 'name' => "file_rename_method",
    'desc' => "{BasePlugin.file_rename_method}",
    'type' => "enum",
    'deft' => &get_default_file_rename_method(), # by default rename imported files and assoc files using this encoding
    'list' => $BasePlugin::file_rename_method_list,
    'reqd' => "no"
  } ];

Solution

  • As Bwmat said it's a reference to an Array of Hash references. Read

    $ man perlref
    

    or

    $ man perlreftut     # this is a bit more straightforward
    

    for if you want to know more about references.

    By the way in fiew words in Perl you can do:

    @array = ( 1, 2 );          # declare an array
    $array_reference = \@array; # take the reference to that array
    $array_reference->[0] = 2;  # overwrite 1st position of @array
    
    $numbers = [ 3, 4 ];        # this is another valid array ref declaration. Note [ ] instead of ( )
    

    the same thing happens with hashes.

    By the way in fiew words in Perl you can do:

    %hash = ( foo => 1, bar => 2 );
    $hash_reference = \%hash; 
    $hash_reference->{foo} = 2;
    
    $langs = { perl => 'cool', php => 'ugly' }; # this is another valid hash ref declaration. Note { } instead of ( )
    

    And... yes, you can dereference these references.

    %{ $hash_reference }
    

    will be treated as it was a hash, so if you want to print the keys of $langs above, you can do:

    print $_, "\n" foreach ( keys %{ $langs } );
    

    To dereference an array ref use @{ } instead of %{ }. Even sub can be dereferenced.

    sub foo
    {
      print "hello world\n";
    }
    
    my %hash = ( call => \&foo );
    
    &{ $hash{call} }; # this allows you to call the sub foo