سؤال

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.

هل كانت مفيدة؟

المحلول 2

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'
          }
        ];

نصائح أخرى

You are not adding to an array, you are adding key/value pairs to the hash inside an array. You can see this by the brackets used in the Data::Dumper output

$VAR1 = [     # <-- this means start of anonymous array ref
          {   # <-- this means start of anonymous hash ref

So basically you have an array of hashes. E.g. $VAR->[0]{'key'} is the syntax you would use.

You should know that your resulting structure is just half the picture. What's more important in this case is the code you used to get there, so that is what you should show.

Also, you should know that there is no "start" and "end" to a hash: A hash is unordered, and there is no way to control the order of keys/values. (By normal means)

That's an array reference containing a single hash reference. You can add values to the hash using:

$arrayref->[0]->{'detail'} = 'Some details';
$arrayref->[0]->{'url'} = 'http://....';

Explanation:

To access the elements in an array from its reference you use the ->. e.g. $arrayref->[0] gives you the first element. This first element is a reference to a hash so again you use -> to access its elements.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top