in reply to Return reference to hash keys

First, you are reinventing the wheel: see uniq in List::MoreUtils and How do I compute the difference of two arrays? How do I compute the intersection of two arrays? in perlfaq4. But this, of course, does not answer your question.

keys returns a list, not an array, and so if you want to return an array reference you necessarily need to create a new array. You could reduce your character and line count by simply returning an anonymous array reference:

sub unique { my @refs = @_; my %files = (); foreach my $ref (@refs) { $files{$_}++ foreach (@$ref); } return [keys %files]; }

For more info, see Making References in perlref.

Replies are listed 'Best First'.
Re^2: Return reference to hash keys
by miketosh (Acolyte) on Nov 30, 2010 at 20:24 UTC

    Thanks! That is exactly what I needed. I didn't know the difference between a LIST and an ARRAY. I guess I still need to learn about it, but your solution for an anonymous array reference is exactly what I was looking for.

    Thanks a million.

    Here is my final code, for what it is worth. Yes, I needed to reinvent the wheel for portability, since getting List::MoreUtils is not an option...
    sub compare { my @refs = @_; my ($all, $inter, $diff); my %files; foreach my $ref (@refs) { foreach (@$ref) { $files{$_}++; } } $all = [ keys %files ]; foreach my $e (@$all) { push @{ $files{$e} > 1 ? $inter : $diff }, $e; } return ($all, $inter, $diff); }
      The difference between a list and an array is discussed a bit in perldata. The short, oversimplified version of it is that lists are values and arrays are variables.

      Regarding not using List::MoreUtils, Yes, even you can use CPAN should have an on-point discussion for consideration.