Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 819
Lukasz Madon Avatar asked Jul 26 '11 15:07

Lukasz Madon


2 Answers

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);
like image 164
jrockway Avatar answered Sep 21 '22 08:09

jrockway


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.

like image 27
awwaiid Avatar answered Sep 22 '22 08:09

awwaiid