Search code examples
perllibsodium

Trouble accessing element from Perl anonymous array


I am trying to use crypto_box_keypair from Crypt::Sodium:

my @keyPair = crypto_box_keypair();

My understanding (confirmed by Data::Dumper) is that Crypt::Sodium returns an anonymous array:

$VAR1 = [
          'k?@ʵ????$p?-0?3',
          '?1????qRo??;???1?'
        ];

But I can't seem to access the individual elements.

say scalar @keyPair;

Returns 1, despite two elements being clearly shown by Data::Dumper?

And

$keyPair[1] 

is undef.


Solution

  • Did you do Dumper(\@keyPair) or Dumper(@keyPair)? I suspect you did the latter, in which case $VAR1 is the first (and only) element of @keyPair. If you want to dump an array, pass a reference to it; it's far easier to grasp that way.

    Continuing with that assumption, crypto_box_keypair appears to return a reference to an array rather than multiple scalars. As such, the usage should be

    my $keyPair = crypto_box_keypair();
    say scalar @$keyPair;
    say $keyPair->[0];
    say $keyPair->[1];