0

I have a Tie::IxHash object that has been initialized as follows:

my $ixh = Tie::IxHash->new('a' => undef, 'b' => undef, 'c' => undef);

and later on I want to assign a list of values qw/1 2 3/ to those three keys. I can't seem to find a way to do that in one statement.

(The reason I'm assigning keys in one step, and values in another, is that this is part of an API and the user may wish, instead, to add values using a (key, value) interface.)

I tried $ixh->Values(0..2) = qw/1 2 3/; but that method doesn't like being on the left hand side.

Of course, I could write a loop using $ixh->Replace(index, value), but I wondered if there were a "bulk" method that I've overlooked.

Chap
  • 3,649
  • 2
  • 46
  • 84

2 Answers2

3
tie my %ixh, Tie::IxHash::, ('a' => undef, 'b' => undef, 'c' => undef);
@ixh{qw( a b c )} = (1, 2, 3);

But it's not really a bulk store; it will result in three calls to STORE.


To access Tie::IxHash specific features (Replace and Reorder), you can get the underlying object using tied.

tied(%ixh)->Reorder(...)

The underlying object is also returned by tie.

my $ixh = tie my %ixh, Tie::IxHash::, ...;
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • So, in this approach, I would use %ixh rather than $ixh throughout my code? Does this mean I couldn't use the "more powerful features" of the OO interface? (Not that I think that would be a problem...) – Chap Jun 10 '13 at 00:19
  • 1
    There's no "powerful" feature that you can't access through the hash interface. There are two Tie::IxHash-specific features you can't, so I added to my node how to call those methods. – ikegami Jun 10 '13 at 06:13
  • Didn't know about tied(). That seems preferable to keeping around two different variables that refer to the same thing (like %ixh and $ixh). And currently I have no need for Replace/Reorder. – Chap Jun 10 '13 at 14:20
1

Does this mean I couldn't use the "more powerful features" of the OO interface?

use strict;
use warnings;
use Tie::IxHash;

my $ixh = tie my %hash, 'Tie::IxHash', (a => undef, b => undef, c => undef);

@hash{qw(a b c)} = (1, 2, 3);

for ( 0..$ixh->Length-1 ) {
  my ($k, $v) = ($ixh->Keys($_), $ixh->Values($_));
  print "$k => $v\n";
}

__OUTPUT__
a => 1
b => 2
c => 3
hwnd
  • 69,796
  • 4
  • 95
  • 132