Lukasz Madon
Lukasz Madon

Reputation: 14994

Hash set in Perl

Consider the following code:

$inFilesToCopy{$filename} = $filename;

I have a hash table where both the key and value are the name of a file. I would like to avoid using extra memory and not store the filename twice.

Is there a set object in Perl?

Upvotes: 7

Views: 6874

Answers (2)

jrockway
jrockway

Reputation: 42674

Set::Object works as you'd expect:

use Set::Object qw(set);

my $files = set();
$files->insert($file);
my @files = $files->members();

You can also do set math:

my $a = set();
$a->insert(...);

my $b = set();
$b->insert(...);

my $only_in_a = $a - $b;
copy_to_b($only_in_a->members);

Upvotes: 11

awwaiid
awwaiid

Reputation: 176

You might consider doing:

$inFilesToCopy{$_} = 1;

and then you can do tests like this:

if($inFilesToCopy{$filename}) { ... }

you can also use 'keys %inFilesToCopy' to get the list of files.

Upvotes: 8

Related Questions