Search code examples
arraysperlhashperl-data-structures

Add index and value to an array in Perl


I'm new in Perl world and hope i get your help here.

let's say I have following array:

trap:  $VAR1 = [
      {
        'oid' => 'enterprises.12356.101.2.0.504',
        'type' => 'IPS Anomaly'
      }
    ];

and I want to add more indexes to it that i get following results:

trap:  $VAR1 = [
      {
        'oid' => 'enterprises.12356.101.2.0.504',
        'type' => 'IPS Anomaly',
        'attackid' => 'ID',
        'detail' => 'Some details',
        'url' => 'http://....'
      }
    ];

So the elements are not added to the end of the array - what is done by push or unshift - I've tried with splicing like but it doesnt work.


Solution

  • You can do something like below, and assuming that you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another as this is array reference containing hash.

    use strict;
    use Data::Dumper;
    use warnings;
    
    my $arr_ref = [ { 'oid' => 'enterprises.12356.101.2.0.504', 'type' => 'IPS Anomaly' } ];
    my %test = ('attackid' => 'ID', 'detail' => 'Some details') ;
    
    @{$arr_ref->[0]}{ keys %test } = values %test;
    print Dumper($arr_ref);
    

    Output:

    $VAR1 = [
              {
                'detail' => 'Some details',
                'attackid' => 'ID',
                'oid' => 'enterprises.12356.101.2.0.504',
                'type' => 'IPS Anomaly'
              }
            ];