Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how can I use Tie::IxHash with a dictionary while 'use strict' is on?

Tags:

perl

I'm trying to create a hash that preserves the order that the keys are added. Under section "Create a hash and preserve the add-order" of this page, it gives a snippet that modifies a hash so when you do keys it returns the keys in the order that you inserted them into the hash.

When I do the following snippet:

use strict;
our %foo;
use Tie::IxHash;
tie (%foo, Tie::IxHash);

It fails with:

Bareword "Tie::IxHash" not allowed while "strict subs" in use at /nfs/pdx/home/rbroger1/tmp.pl line 4.
Execution of /nfs/pdx/home/rbroger1/tmp.pl aborted due to compilation errors.

How can I get Tie::IxHash to work when use strict is on?

dsolimano's Example worked.

use strict;
our %foo;
use Tie::IxHash;
tie (%foo, "Tie::IxHash");

$foo{c} = 3;
$foo{b} = 2;
$foo{a} = 1;

print keys(%foo);

prints:

cba

without the tie...Tie::IxHash line it is

cab
like image 395
Ross Rogers Avatar asked Feb 25 '10 02:02

Ross Rogers


2 Answers

The second argument to tie is a string, so try

use strict;
our %foo;
use Tie::IxHash;
tie (%foo, 'Tie::IxHash');
like image 161
dsolimano Avatar answered Oct 19 '22 20:10

dsolimano


Using quotes eliminates the error:

use strict; 
our %foo; 
use Tie::IxHash; 
tie (%foo, "Tie::IxHash"); 

It is not mentioned in the POD, but it is used in the examples on CPAN.

See also tie.

like image 5
toolic Avatar answered Oct 19 '22 20:10

toolic